When I use the following code the loop is iterating twice and I am getting error message as "The variable name '#projectName1' has already been declared. Variable names must be unique within a query batch or stored procedure." and resetting all the values of the table in the datagridview as well as in the table. Actually I want to update the DataGridView in the form itself by selecting the cell and it should reflect the same in the database too.
private void btnUpdate_Click(object sender, EventArgs e)
{
SqlConnection con = Helper.getconnection();
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
string myCmd = string.Empty;
foreach (DataGridViewRow myDgrow in dataGridView2.Rows)
{
myCmd = "Update Details set ProjectName='" + myDgrow.Cells["ProjectName"].Value + "', Description = '" + myDgrow.Cells["Description"].Value + "', DateStarted='" + myDgrow.Cells["DateStarted"].Value + "',TeamSize='" + myDgrow.Cells["TeamSize"].Value + "',Manager='" + myDgrow.Cells["Manager"].Value + "'";
cmd.Parameters.AddWithValue("#projectName1", myDgrow.Cells["ProjectName"].Value);
cmd.Parameters.AddWithValue("#Description1", myDgrow.Cells["Description"].Value);
cmd.Parameters.AddWithValue("#DateStarted1", myDgrow.Cells["DateStarted"].Value);
cmd.Parameters.AddWithValue("#TeamSize1", myDgrow.Cells["TeamSize"].Value);
cmd.Parameters.AddWithValue("#Manager1", myDgrow.Cells["Manager"].Value);
cmd.CommandText = myCmd;
cmd.ExecuteNonQuery();
dataGridView2.Update();
myCmd = string.Empty;
}
DataTable details = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
try
{
da.Update(details);
}
catch (Exception exceptionObj)
{
MessageBox.Show(exceptionObj.Message.ToString());
}
}
You are using foreach loop and adding the parameters each time to the same command. Either clear the parameters each time you iterate in the loop or create a new command each time..
Related
I am creating a basic app for adding and displaying customer information using windows forms in visual studio. i have set it up so i am able to display the contents of the database in a gridview and also add to the database which you can see the code for below. what i am stuck on at the moment is updating the customers information. I want to search the database by customerID which will be entered by the user in a textbox, and display that specific customers details into their relevent textboxes which i can then edit and save.
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"INSERT INTO customer (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance)";
cmd.Parameters.AddWithValue("setTitle", cb_title.Text);
cmd.Parameters.AddWithValue("setFirstname", txtFirst_Name.Text);
cmd.Parameters.AddWithValue("setLastname", txtSurname.Text);
cmd.Parameters.AddWithValue("setDOB", dtp_DOB.Text);
cmd.Parameters.AddWithValue("setNICode", txtNI_Code.Text);
cmd.Parameters.AddWithValue("setEmail", txtEmail.Text);
cmd.Parameters.AddWithValue("setPassword", txtPassword.Text);
cmd.Parameters.AddWithValue("setAllowance", txtAllowance.Text);
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Added");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
That's what I have for adding a new customer which works fine
using (SQLiteCommand cmd = conn.CreateCommand())
{
// adds customers details to the database
cmd.CommandText = #"UPDATE customer SET (title, " + "firstname, " + "lastname, " + "dob, " + "nicode, " + "email, " + "password, " + "allowance) VALUES (#setTitle, #setFirstname, #setLastname, #setDOB, #setNICode, #setEmail, #setPassword, #setAllowance) WHERE custid = #recd";
cmd.Parameters.AddWithValue("title", cb_title_update.Text);
cmd.Parameters.AddWithValue("firstname", txtFirst_Name_update.Text);
cmd.Parameters.AddWithValue("lastname", txtSurname_update.Text);
cmd.Parameters.AddWithValue("dob", dtp_DOB_update.Text);
cmd.Parameters.AddWithValue("nicode", txtNI_Code_update.Text);
cmd.Parameters.AddWithValue("email", txtEmail_update.Text);
cmd.Parameters.AddWithValue("password", txtPassword_update.Text);
cmd.Parameters.AddWithValue("allowance", txtAllowance_update.Text);
cmd.Parameters.AddWithValue("recd", Convert.ToInt32(txtSearch.Text));
int recordsChanged = cmd.ExecuteNonQuery();
MessageBox.Show("Customer Updated");
conn.Close();
Customers customers = new Customers();
customers.Show();
this.Hide();
}
And that's the code I have so far for updating the database, but I can not figure out how to retrieve the customer data and display it into the textboxes, any help or guidance would be appreciated
Your Update statement is not correct. Try the following.
cmd.CommandText =#"UPDATE customer
SET title = #setTitle,
firstname = #setFirstname,
lastname = #setLastname
dob = #setDOB,
nicode = #setNICode,
email = #setEmail,
password = #setPassword,
allowance = #setAllowance
WHERE custid = #recd";
It is a bit different from an Insert. Each field is set to a new value. You don't need all that concatenation. This is a literal string.
Of course, in a real application you would NEVER store passwords as plain text.
To get the value of a certain column from a certain row, you can try to call method SqlCommand.ExecuteReader.
Here assume you want to get the the customer password.
string connectionstring = #"connectin string";
private void btnSearch_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "Select * from customer where customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
conn.Open();
try
{
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
if (reader.HasRows)
{
if (reader.Read())
{
// get password column value
textBoxPWD.Text = reader["password"].ToString();
}
}
else
{
Console.WriteLine("no such record");
}
}
catch (Exception ex)
{
Console.WriteLine("\nError:\n{0}", ex.Message);
}
}
}
As to update the record,
private void btnUpdate_Click(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(connectionstring))
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandText = "UPDATE customer SET password = #cusPWD WHERE customerID = #cusID";
cmd.Parameters.AddWithValue("#cusID", textBoxID.Text);
cmd.Parameters.AddWithValue("#cusPWD", textBoxPWD.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
I am trying to Display a name in the textbox from the database if the ID entered by the user matches the record in the MS ACCESS DATABASE.
I'm getting the error Data type mismatch in criteria expression at the line int count = Convert.ToInt32(cmd.ExecuteScalar());
The following is my aspx.cs code-
protected void Button1_Click(object sender, EventArgs e)
{
clear();
idcheck();
DataTable dt = new DataTable();
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT [DoctorName] FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
OleDbDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
TextBox2.Text = dr["DoctorID"].ToString();
dr.Close();
con.Close();
}
}
public void idcheck()
{
OleDbConnection con = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\dfg\fd\Visual Studio 2010\WebSites\WebSite21\App_Data\UPHealth.mdb");
con.Open();
str = "SELECT count(DoctorName) FROM [DoctorInfo] WHERE DoctorID='" + TextBox1.Text.Trim() + "'";
OleDbCommand cmd = new OleDbCommand(str, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
if (count > 0)
{
Label21.Text = "Doctor Name";
}
else
{
Label21.Text = "Id Does not Exist";
}
}
void clear()
{
TextBox2.Text = "";
}
I guess that is because you as passing in an ID, which is usually a numeric value, as a text field:
DoctorID='" + TextBox1.Text.Trim() + "'
Which should be:
DoctorID=" + TextBox1.Text.Trim()
Another problem arises, since you are vulnerable to SQL injection. What if the text box contained 1; delete users? Then your entire users table would be empty. The lesson learned: use parameterized queries!
Then you can express the SQL as:
DoctorID= ?
And add the parameter to the request:
cmd.Parameters.AddWithValue("?", TextBox1.Text.Trim());
I have two methods, one to insert, update and delete and a second is checking whether data already exists in my database or not. The main purpose of all code is that I don't want to insert duplicate data into the database.
public class DAL : System.Web.UI.Page
{
SqlConnection connection;
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
public int numofrows;
//Connection Method
public void Connection()
{
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
connection.Open();
}
//This Method will Insert,Update and Delete in Database
public void InsertUpdateDelete(string query)
{
////connection = new SqlConnection("Data Source=IM-82B70624D72D;Initial Catalog=AppointmentScheduler;User ID=sa;Password=za3452432760za");
//connection = new SqlConnection(connectionString);
//connection.Open();
this.Connection();
cmd = new SqlCommand(query, connection);
numofrows = cmd.ExecuteNonQuery();
connection.Close();
}
//This Method will read data From Database
public DataTable ReadData(string Query)
{
this.Connection();
da = new SqlDataAdapter(Query, connection);
dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
Response.Redirect("Data already Exist");
}
return dt;
}
}
I have to use both above code in index.aspx. How can I use both above code in index.aspx?
I tried to use but that is not working.
index.aspx code:
protected void btnSaveDays_Click(object sender, EventArgs e)
{
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id='" + DropDownListDays.SelectedValue + "'";
dal.ReadData(this.query);
this.query = "INSERT INTO Dayss VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
dal.InsertUpdateDelete(this.query);
Response.Write("Day Inserted Successfully");
}
But this code is not working and generating error
Conversion failed
not Day_Id is int, and Dayss have two columns. One is id and second is
name
Then there is no point to use single quotes with int typed column value. Single quotes is for character column values.
this.query = "SELECT DaysName FROM Dayss WHERE Day_Id = " + DropDownListDays.SelectedValue ;
And if you want to insert just one column, you need specify your column name in your Dayss table like;
this.query = "INSERT INTO Dayss (YourColumnName) VALUES ('" + DropDownListDays.SelectedItem.Text + "')";
Take a look INSERT (Transact-SQL)
In page load I'm loading a drop down list with names from a postgreSQL database, using SQL.
Later in the code I want to save the selected value in the drop down list into a string variable.
That won't happen. What happens is the first value in the list (index 0) always saves, no matter of which I have selected.
Heres is page load (works fine):
protected void Page_Load(object sender, EventArgs e)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
Here is Button1_Click. I want to save the selected value into string variable syv.
protected void Button1_Click(object sender, EventArgs e)
{
string syv = ddPersons.SelectedItem.Text;
string name = txtName.Text;
int studentid = 0;
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=sSYS;User Id=postgres;Password=postgres;");
conn.Open();
string sql = "SELECT id FROM tbl_student WHERE name = '" + name + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
studentid = (int)dr["id"];
}
}
I have tried
string syv = ddPersons.SelectedItem.Text;
string syv = ddPersons.SelectedItem.Value;
string syv = ddPersons.Text;
string syv = ddPersons.SelectedValue;
It might be that ViewState is saving the state of your page. Why don't you include the following line in your Page_Load method:
if ( !IsPostBack)
{
NpgsqlConnection conn = new NpgsqlConnection("Server=127.0.0.1;Port=5432;Database=SYS;User Id=postgres;Password=postgres;");
conn.Open();
NpgsqlCommand command = new NpgsqlCommand("SELECT name FROM tbl_syv ORDER BY name", conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
ddPersons.Items.Add((string)dr["name"] + " " + " ");
}
}
It will prevent the Page_Load to populate duplicate items every time someone clicks on the button and prevents the ViewState to interfere with the state of your controls.
I've got a C# project where I'm trying to export the results of a datagrid. Sometimes the data gets quite large, so rather than re-executing the code I want to dump the dataset into a session variable.
This works perfectly in most of my projects. One example from a project where I use this is:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection sqlconnectionStatus = new SqlConnection(str);
string DDL_Value = Convert.ToString(Request.QueryString["DDL_Val"]);
//Use the ClassTesting class to determine if the dates are real, and fill in today's date if they're blank
string StDt_Value = ClassTesting.checkFields(Request.Form["txtStartDate"], "Date");
string EnDt_Value = ClassTesting.checkFields(Request.Form["txtEndDate"], "Date");
//string StDt_Value = Convert.ToString(Request.QueryString["StDt_Val"]);
//string EnDt_Value = Convert.ToString(Request.QueryString["EnDt_Val"]);
string BTN_Value;
// Because the date is stored as an INT, you have to request the string and then
// convert it to an INT
string StDT_Vals = Request.QueryString["StDt_Val"].ToString();
string EnDT_Vals = Request.QueryString["EnDt_Val"].ToString();
//sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
//sqlquery = sqlquery + "from ClosedClaims_MERGE CCM ";
sqlquery = "Select PROC_NM as 'Agent Name', AdminLevel as Role, Count(DISTINCT Claim_ID) as 'Count of Claims Reviewed', Spare as AgentID ";
sqlquery = sqlquery + "from (SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM ClosedClaims_MERGE ";
sqlquery = sqlquery + "UNION SELECT DISTINCT Spare, SpareFinished, CLAIM_ID FROM tblAuditing) CCM ";
sqlquery = sqlquery + "LEFT JOIN PROC_LIST PL ON CCM.Spare = PL.LOGIN ";
sqlquery = sqlquery + "WHERE CCM.SpareFinished >= '" + StDt_Value + "' AND CCM.SpareFinished <= '" + EnDt_Value + "' ";
sqlquery = sqlquery + "GROUP BY Spare, PROC_NM, AdminLevel ";
sqlquery = sqlquery + "ORDER BY Count(Claim_ID) DESC";
SqlConnection con = new SqlConnection(str);
SqlCommand cmd = new SqlCommand(sqlquery, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
DataSet ds = new DataSet();
adapter.Fill(ds, "dsEffVol");
// Add this to a session variable so the datagrid won't get NULLed out on repost
Session["SSEffVol"] = ds;
// Perform the binding.
grdEffVol.Attributes.Add("style", "overflow:auto");
//GridView_WODetails.Attributes.Add("style", "table-layout:fixed");
grdEffVol.AutoGenerateColumns = true;
grdEffVol.DataSource = ds;
grdEffVol.DataBind();
}
I've got a new project where I'm not using SQL strings, but instead I'm pulling data based on SQL Server Stored Procedures. The code block there is:
protected void btnSubmit_OnClick(object sender, EventArgs e)
{
List<ReportData> myReportData = new List<ReportData>();
using (SqlConnection connection1 = new SqlConnection(str2))
{
//Query the Reports table to find the record associated with the selected report
using (SqlCommand cmd = new SqlCommand("SELECT * from RM_tblManagerReports WHERE ReportID = " + cboFilterOption.SelectedValue + "", connection1))
{
connection1.Open();
using (SqlDataReader DT1 = cmd.ExecuteReader())
{
while (DT1.Read())
{
//Read the record into an "array", so you can find the SProc and View names
int MyRptID = Convert.ToInt32(DT1[0]);
string MyRptName = DT1[1].ToString();
string MyRptSproc = DT1[2].ToString();
string MySQLView = DT1[3].ToString();
string MyUseDates = DT1[4].ToString();
//Run the Stored Procedure first
SqlConnection connection2 = new SqlConnection(str2);
SqlCommand cmd2 = new SqlCommand();
cmd2.CommandType = CommandType.StoredProcedure;
cmd2.CommandText = "" + MyRptSproc + "";
cmd2.Connection = connection2;
//Set up the parameters, if they exist
if (MyUseDates != "N")
{
cmd2.Parameters.Add("#StDate", SqlDbType.Date).Value = DateTime.Parse(txtStDate.Value);
cmd2.Parameters.Add("#EnDate", SqlDbType.Date).Value = DateTime.Parse(txtEnDate.Value);
}
else
{
}
try
{
connection2.Open();
GridView_Reports.EmptyDataText = "No Records Found";
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
GridView_Reports.DataBind();
// Add this to a session variable so the datagrid won't get NULLed out on repost
GridView_Reports.DataBound += GridView_Reports_RowDataBound;
}
catch (Exception ex)
{
ScriptManager.RegisterStartupScript(btnSubmit, typeof(Button), "Report Menu", "alert('There is no View associated with this report.\\nPlease contact the developers and let them know of this issue.')", true);
Console.WriteLine(ex);
return;
}
finally
{
connection2.Close();
connection2.Dispose();
}
}
}
}
}
}
I'm kind of guessing my way through this, and I'm not sure if I'm reading the data into a dataset properly. The page is shutting down, and I'm pretty sure the problem is in the lines:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Quite honestly, I've googled SqlDataReader vs SqlDataAdapter and can't really find anything, but I need to fill the session variable in the second example and also have the datagrid populate properly. So, in essence, I need to put the results of a Stored Procedure into a dataset. Can anyone offer suggestions on what I'm doing wrong?
I'm pretty sure most controls don't accept readers in their DataSource property. Plus the majority of readers are forward-only, so although you're trying to store the reader as a session variable, chances are you would only be able to read it once.
Why do you want to use a reader for this when your post seems to indicate that you know you need to use a DataSet? Why not just use an adapter the way you show in your first post? Adapters work fine with commands that use sprocs.
Instead of:
SqlDataReader dr = cmd2.ExecuteReader(CommandBehavior.CloseConnection);
Session["SSRptMenu"] = dr;
GridView_Reports.DataSource = dr;
Just use:
var adapter = new SqlDataAdapter(cmd2);
var ds = new DataSet();
adapter.Fill(ds, "MyTableName");
Session["SSRptMenu"] = ds;
GridView_Reports.DataSource = ds;