Data won't update (database is SQL Server) - c#

I have a problem in updating my data.
I have Home.aspx.cs and a class HomeClass.cs. I have a gridview in which I want to do my updating but it doesn't work.
It won't return the successful message and I also checked my SQL Server database but there's no changes.
This is my Home.aspx.cs:
protected void DataGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
GridViewRow row = DataGridView.Rows[e.RowIndex];
// get old data
HiddenField hidedescription = row.FindControl("hiddendescription") as HiddenField;
HiddenField hidepkgcode = row.FindControl("hiddenpkgcode") as HiddenField;
HiddenField hideoprcode = row.FindControl("hiddenoprcode") as HiddenField;
// get new data
DropDownList Ed_description = DataGridView.Rows[e.RowIndex].FindControl("Editdescription") as DropDownList;
TextBox Ed_pkgcode = DataGridView.Rows[e.RowIndex].FindControl("Editpkgcode") as TextBox;
TextBox Ed_oprcode = DataGridView.Rows[e.RowIndex].FindControl("Editoprcode") as TextBox;
string Message = obj.Update_Data(Ed_description.SelectedItem,
Ed_pkgcode,
Ed_oprcode,
hidedescription.Value,
hidepkgcode.Value,
hideoprcode.Value);
Fill_Grid();
Literal1.Text = Message;
}
catch (Exception ex)
{
}
}
void Fill_Grid()
{
try
{
DataGridView.DataSource = obj.Get_Data();
DataGridView.DataBind();
}
catch (Exception ex)
{
}
}
And this is my HomeClass.cs class:
static string Connect = WebConfigurationManager.ConnectionStrings["CONSTRING"].ConnectionString;
SqlConnection con = new SqlConnection(Connect);
SqlCommand cmd;
SqlDataAdapter adap;
DataTable dt;
public string Update_Data(ListItem listItem,
TextBox Ed_pkgcode,
TextBox Ed_oprcode,
string hidedescription,
string hidepkgcode,
string hideoprcode)
{
// update data
string getnewType = listItem.Text;
if (getnewType == "Data 1")
{
getnewType = "Y";
}
if (getnewType == "Data 2")
{
getnewType = "N";
}
// old data
if (hidedescription == "Data 1") { hidedescription = "Y"; }
if (hidedescription == "Data 2") { hidedescription = "N"; }
con.Open();
cmd = new SqlCommand("Update PAORStdTime set type='" + getnewType +
"', pkgcode='" + Ed_pkgcode.Text +
"', oprcode='" + Ed_oprcode.Text +
"' where type= '" + hidedescription +
"' and pkgcode ='" + hidepkgcode +
"' and oprcode ='" + hideoprcode + "'" , con);
cmd.ExecuteNonQuery();
con.Close();
return "Updated successfully";
}

where type = hidedescription
and pkgcode = hidepkgcode
and pkgcode = hideoprcode
There is no way that pkgcode will be equal to both hidepkgcode and hideoprcode. I believe the code below is what you want.
where type = hidedescription
and pkgcode = hidepkgcode
and oprcode = hideoprcode

Related

How to update SQL Table Using DataGridView Values in C#?

enter image description hereI tried to update selected columns of SQL Database table which from DataGridView. But it said my input string is wrong.So how to fix this.(PO_No is the primary key of PO table and it has identity value and also it is the foreign key of PO_Cart table)
public void UpdatePOCartTable(int PO_No,string ISBN_No,int OrderQuantity, decimal UnitPrice, decimal Total)
{
DynamicConnection con = new DynamicConnection();
con.mysqlconnection();
string query = "UPDATE TBL_PO_Cart"
+ " SET ISBN_No = #ISBN_No, OrderQuantity= #OrderQuantity,"
+ "UnitPrice= #UnitPrice, Total=#Total"
+ "WHERE PO_No = #PO_No";
con.sqlquery(query);
con.cmd.Parameters.Add(new SqlParameter("#PO_No", SqlDbType.Int));
con.cmd.Parameters["#PO_No"].Value = PO_No;
con.cmd.Parameters.Add(new SqlParameter("#ISBN_No", SqlDbType.NVarChar));
con.cmd.Parameters["#ISBN_No"].Value = ISBN_No;
con.cmd.Parameters.Add(new SqlParameter("#OrderQuantity", SqlDbType.NVarChar));
con.cmd.Parameters["#OrderQuantity"].Value = OrderQuantity;
con.cmd.Parameters.Add(new SqlParameter("#UnitPrice", SqlDbType.Money));
con.cmd.Parameters["#UnitPrice"].Value = UnitPrice;
con.cmd.Parameters.Add(new SqlParameter("#Total", SqlDbType.Money));
con.cmd.Parameters["#Total"].Value = Total;
con.nonquery();
}
private void btnedit_Click(object sender, EventArgs e)
{
DynamicConnection con = new DynamicConnection();
try
{
if (txtPONo.Text != "" || cmbsupID.Text != "" || date1.Text != "" || requireddate.Text != "" || txtgrandTotal.Text != "")
{
PurchaseOrder PO = new PurchaseOrder();
for (int i = 0; i < dataGridView1.Rows.Count-1; i++)
{
PO.UpdatePOCartTable(Convert.ToInt32(txtPONo.Text),dataGridView1.Rows[i].Cells[1].Value.ToString(), Convert.ToInt32(dataGridView1.Rows[i].Cells[2].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[3].Value.ToString()), Convert.ToDecimal(dataGridView1.Rows[i].Cells[4].Value.ToString()));
}
}
else
{
MessageBox.Show("Please Provide Details!");
}
dataGridView1.Rows.Clear();
ClearData();
retviewPO_No();
MessageBox.Show("Record Updated Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Error Occured" + ex.Message);
}
}
When Updating SQL I normally use the following code:
String CommandLine = "UPDATE CA_temp_data SET TimePast=#selectTot WHERE TicketNumber=#id";
using (SqlConnection Conn = new SqlConnection("Data Source=" + hostString + ";User ID=" + usernamestring + ";Password=" + sqlpassword))
{
try
{
SqlCommand cmd = new SqlCommand(CommandLine, Conn);
cmd.Parameters.AddWithValue("#id", ticket);
cmd.Parameters.AddWithValue("#selectTot", time);
using (Conn)
{
Conn.Open();
cmd.ExecuteNonQuery();
Conn.Close();
}
}
catch (System.Exception excep)
{
}

Table not updated in database after changing values from Textbox linked to Selected Item from ListView

This is how it works. I select a row from my listview then I will click "Edit" button which the values from the selected item will also be shown in the registration form. The "Register" button will now then changed to "Update". I am trying to update my customers table after changing inputs from the textboxes on my registration form but there are no changes in my database.
I receive no errors but I might have missed something here.
This is my code here:
private void btnRfrsh_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "SELECT Cust_Lname, Cust_Fname, Cust_MI, Birthdate, Age, Sex, Passport_ID, Address, Contact_Num, Nationality from customers where removed = 0";
MySqlCommand select = new MySqlCommand(query, connect);
MySqlDataReader refresh = select.ExecuteReader();
while (refresh.Read())
{
ListViewItem item;
item = new ListViewItem(refresh.GetString(0));
item.SubItems.Add(refresh.GetString(1));
item.SubItems.Add(refresh.GetString(2));
item.SubItems.Add(refresh.GetString(3));
item.SubItems.Add(refresh.GetString(4));
item.SubItems.Add(refresh.GetString(5));
item.SubItems.Add(refresh.GetString(6));
item.SubItems.Add(refresh.GetString(7));
item.SubItems.Add(refresh.GetString(8));
item.SubItems.Add(refresh.GetString(9));
lviewCust.Items.Add(item);
}
if (refresh.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
private void btnEdit_Click(object sender, EventArgs e)
{
if (lviewCust.SelectedItems.Count > 0)
{
ListViewItem item = lviewCust.SelectedItems[0];
cust_fname.Text = item.SubItems[0].Text;
cust_lname.Text = item.SubItems[1].Text;
cust_mi.Text = item.SubItems[2].Text;
//DateTime bdate = Convert.ToDateTime(item.SubItems[3].Text);
String bdate_string = item.SubItems[3].Text;
DateTime bdate = DateTime.ParseExact(bdate_string, "dd-MM-yyyy", null);
cust_bdate.Value = bdate;
cust_age.Text = item.SubItems[4].Text;
cust_sex.Text = item.SubItems[5].Text;
cust_passid.Text = item.SubItems[6].Text;
cust_nation.Text = item.SubItems[9].Text;
cust_add.Text = item.SubItems[7].Text;
cust_contact.Text = item.SubItems[8].Text;
}
cust_fname.ReadOnly = true;
cust_lname.ReadOnly = true;
cust_mi.ReadOnly = true;
cust_passid.ReadOnly = true;
btnReg.Text = "Update";
btnReg.Name = "btnUpdate";
btnReg.Click -= this.btnReg_Click;
btnReg.Click += this.btnUpdate_Click;
}
private void btnUpdate_Click(object sender, EventArgs e)
{
try
{
con = "datasource=localhost; port=3306; database=cam_air_db; uid=root;";
connect = new MySqlConnection(con);
connect.Open();
string query = "UPDATE customers SET Age = '" + this.cust_age.Text + "', Nationality = '" + this.cust_nation.Text + "', Address = '" + this.cust_add.Text + "', Contact_Num = '" + this.cust_contact.Text + "' WHERE Cust_Fname = '" + this.cust_fname.Text + "' and Cust_Lname = '" + this.cust_lname.Text + "'";
MySqlCommand update = new MySqlCommand(query, connect);
MySqlDataReader updte = update.ExecuteReader();
MessageBox.Show("Customer Info Updated Successfully");
if (updte.Read())
{
connect.Close();
}
else
{
connect.Close();
}
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
cust_fname.Clear();
cust_lname.Clear();
cust_mi.Clear();
cust_bdate.Value = DateTime.Now;
cust_age.Clear();
cust_passid.Clear();
cust_add.Clear();
cust_contact.Clear();
cust_nation.Clear();
cust_fname.ReadOnly = false;
cust_lname.ReadOnly = false;
cust_mi.ReadOnly = false;
cust_passid.ReadOnly = false;
btnReg.Text = "Register";
btnReg.Name = "btnReg";
btnReg.Click -= this.btnUpdate_Click;
btnReg.Click += this.btnReg_Click;
}
}
}
First, I think you should use ExecuteNonQuery() instead of ExecuteReader().
You call ExecuteReader() when you execute a sql command that returns something (such as SELECT).
When you call a command that doesn't return anything (such as INSERT, UPDATE, DELETE, etc.), you should call ExecuteNonQuery().
See the details here.
Second, I think you should check the result before alert "successfully". ExecuteNonQuery() returns the number of rows affected, you can check this to determine success or not.

I can't seem to get my Gridview to update to my SQL Server database

Here is my current code behind for the OnRowUpdating event and SQL statement to update the database. It is throwing an exception:
System.NullReferenceException: Object reference not set to an instance of an object.error
Code:
protected void GV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtSu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox1"); // each textbox refers to the Am then Pm day
TextBox txtSu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox2");// sun pm
TextBox txtMo = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox3");// mon am
TextBox txtMo1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox4");//mon pm
TextBox txtTu = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox5");
TextBox txtTu1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox6");
TextBox txtWe = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox7");
TextBox txtWe1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox8");
TextBox txtTh = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox9");
TextBox txtTh1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox10");
TextBox txtFr = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox11");
TextBox txtFr1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox12");
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
TextBox txtSa1 = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox14");
string sql = "UPDATE tblEMPLOYEE SET EmployeeID=#ID, " +
"AvailSun=#AvSu, " +
"AvailSun1=#AvSu1, " +
"AvailMon=#AvMo, " +
"AvailMon1=#AvMo1, " +
"AvailTues=#AvTu, " +
"AvailTues1=#AvTu1, " +
"AvailWedn=#AvWe, " +
"AvailWedn1=#AvWe1, " +
"AvailThurs=#AvTh, " +
"AvailThurs1=#AvTh1, " +
"AvailFri=#AvFr, " +
"AvailFri1=#AvFr1, " +
"AvailSat=#AvSa, " +
"AvailSat1=#AvSa1 " +
"WHERE EmployeeID=#ID";
CMethods.executeNonQuery(sql, "#ID", txtID.Text, "#AvSu", txtSu.Text, "#AvSu1", txtSu1.Text, "#AvMo", txtMo.Text, "#AvMo1", txtMo1.Text, "#AvTu", txtTu.Text, "#AvTu1", txtTu1.Text, "#AvWe", txtWe.Text, "#AvWe1", txtWe1.Text, "#AvTh", txtTh.Text, "#AvTh1", txtTh1.Text, "#AvFr", txtFr.Text, "#AvFr1", txtFr1.Text, "#AvSa", txtSa.Text, "#AvSa1", txtSa1.Text, "#ID", ID);
GV.EditIndex = -1;
fillUsers();
}
private void fillUsers()
{
GV.DataSource = CMethods.returnTable("SELECT * FROM tblEMPLOYEE WHERE EmployeeID=" + lblEmployee.Text);
GV.DataBind();
}
In Cmethods
public static class CMethods
{
public static DataTable returnTable(String CommandText, params Object[] values)
{
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "tbl");
return ds.Tables["tbl"];
}
public static bool executeNonQuery(String CommandText, params Object[] values)
{
bool bln = true;
SqlConnection con =
new SqlConnection(ConfigurationManager.ConnectionStrings["Provider"].ConnectionString);
SqlCommand cmd = new SqlCommand(CommandText, con);
for (int i = 0; i < values.Length; i += 2)
{
cmd.Parameters.AddWithValue((String)values[i], values[i + 1]);
}
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
bln = false;
}
finally
{
con.Close();
}
return bln;
}
public static double returnValue(string str)
{
double dblTemp = 0.0D;
string strTemp = String.Empty;
bool blnFirstDec = false;
bool blnFirstNeg = false;
for (int i = 0; i < str.Length; i++)
{
if (str.Substring(i, 1) == "-")
{
blnFirstNeg = true;
}
if (IsNumeric(str.Substring(i, 1)) || str.Substring(i, 1) == ".")
{
if (str.Substring(i, 1) == ".")
{
if (!blnFirstDec)
{
blnFirstDec = true;
strTemp += ".";
}
}
else
{
strTemp += str.Substring(i, 1);
}
}
}
FindControl control may not return control if you not provide correct control id
for example you have given txtBo13(missing x) but actually you may have txtBox13,
so below code return null for txtSa
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBo13");
when you call Text property of txtSa you will get NullReferenceException
if you have given id as txtBox13, change the code accordingly
TextBox txtSa = (TextBox)GV.Rows[e.RowIndex].FindControl("txtBox13");
And also you may have forgot to set #student parameter value

Get selected value of a dynamically generated drop down/checkbox in c#

I have been making a UI panel and have dynamic data for input to the interface.
For this I want a filter an SQL query based on user selected valus of several SQL querys.
For a prototype:
I generated the panel and got the data to appear no problems, but since I do not know how many filters I will have until I look at the first query I made the checkboxes and dropdowns on the filter dynamically.
The problem I have is I cannot access the user selected values in the dropdowns or the checkboxes.
I assigned unique ID's to each element so the fastest solution would be the c# equivalent of getElementByID?
I will post some of the code below:
protected string SQConnWhere(string TableName = "Nonya", string FieldName = "Error!!!", int i=0)
{
string ConnectionString = "real string removed";
cmdText = #"SELECT DISTINCT " + FieldName + " FROM tablenamechangedfromrealonetoprotectthe innocent";
Label myLabel = new Label();
Label myLabelA = new Label();
CheckBox myCheckBox = new CheckBox();
DropDownList myList = new DropDownList();
myList.ID = "myList" + i;
myCheckBox.ID = "myCheckBox" + i;
myLabel.ID = "myLabel" + i;
myLabelA.ID = "myLabelA" + i;
myLabel.Text = FieldName;
PlaceHolder1.Controls.Add(myLabel);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(myList);
myCheckBox.Text = "Use This Field in Filter?";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn);
DataSet ds2 = new DataSet();
adapter.Fill(ds2);
myList.DataSource = ds2;
myList.DataTextField = FieldName;
myList.DataBind();
ViewState["Data"] = ds2;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
PlaceHolder1.Controls.Add(myCheckBox);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
//May not need this?
//filterList.Add(FieldName);
myLabelA.Text = cmdText;
PlaceHolder1.Controls.Add(myLabelA);
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
PlaceHolder1.Controls.Add(new LiteralControl("<br />"));
//myCheckBox.CheckedChanged += new EventHandler(UpdatemyCheckBox);
//pnlCheckList.Controls.Add(myCheckBox);
// register the control to cause asynchronous postbacks
//ScriptManager.GetCurrent(this).RegisterAsyncPostBackControl(myCheckBox);
//Label4.Text = FieldName;
return cmdText;
}
P.S. This is my first post despite browsing the website for a long time, thanks for all the help thus far!!!
I solved it using
ManualSQConnWhere(DropDownList1, myTable, "Run_ID", CheckBox1);
ManualSQConnWhere(DropDownList2, myTable, "Job_Status", CheckBox2);
ManualSQConnWhere(DropDownList3, myTable, "Job_Plan", CheckBox3);
protected string ManualSQConnWhere(DropDownList myList, string TableNameWeb2, string FieldName, CheckBox myCheckBox)
{
string ConnectionString = "Data Source=xxxxx;Initial Catalog=xxxxx;Integrated Security=True";
cmdText = #"SELECT DISTINCT " + FieldName + " FROM " + TableNameWeb2;
DataSet dbWeb2 = new DataSet();
myList.AutoPostBack = false;
//myList.ViewStateMode = ViewStateMode.Enabled;
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
try
{
SqlDataAdapter adapter = new SqlDataAdapter(cmdText, conn);
adapter.Fill(dbWeb2);
ViewState["Data"] = dbWeb2;
}
catch (Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
}
myList.AppendDataBoundItems = true;
myList.DataSource = dbWeb2;
myList.DataTextField = FieldName;
myList.Items.Add(new ListItem("<None Selected>", string.Empty));
if (dbWeb2.Tables.Count > 0)
{
myList.DataBind();
}
else
{
Label1.Text = "Error on the SQL Query" + cmdText;
return cmdText;
}
myCheckBox.Text = FieldName;
return cmdText;
}
This code propogated the dropdowns and I simply entered the tags for them

Timeout connection error while executing this piece of code in ASP.NET 2.0 and C#

I am using the below code to grab the page tiles, meta description from database created in SQL Server 2005. My site is built with ASP.NET 2.0 and C#.
On page_load I am executing this code:
string query = "select MetaDescription, MetaKeywords, H1Text, Ptitle, H2Text FROM SeoText Where CatalogItemId ='" + this.CurrentEnsemble.ItemId + "'";
SqlConnection myconnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DBconnection"].ConnectionString);
SqlCommand SqlCmd = null;
SqlCmd = new SqlCommand(query, myconnection);
SqlDataAdapter ad = new SqlDataAdapter(SqlCmd);
DataTable dt = new DataTable();
ad.Fill(dt);
if (dt.Rows[0]["Ptitle"].ToString() == "")
{
this.Page.Title = this.CurrentEnsemble.Title;
}
else
{
this.Page.Title = this.CurrentEnsemble.Title + " " + dt.Rows[0]["Ptitle"].ToString();
}
HtmlMeta metaDesc = (HtmlMeta)Page.Header.FindControl("metaDesc");
if (dt.Rows[0]["MetaDescription"].ToString() == "")
{
metaDesc.Attributes.Add("Content", this.CurrentEnsemble.Title );
}
else
{
metaDesc.Attributes.Add("Content", dt.Rows[0]["MetaDescription"].ToString());
}
HtmlMeta metaKey = (HtmlMeta)Page.Header.FindControl("metaKey");
if (dt.Rows[0]["MetaKeywords"].ToString() == "")
{
metaKey.Attributes.Add("Content", "site general text");
}
else
{
metaKey.Attributes.Add("Content", dt.Rows[0]["MetaKeywords"].ToString());
}
HtmlGenericControl h1 = (HtmlGenericControl)Master.Master.Master.FindControl("h1top");
if (dt.Rows[0]["H1Text"].ToString() == "")
{
h1.InnerText = "site general text";
}
else
{
h1.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H1Text"].ToString();
}
HtmlGenericControl h2 = (HtmlGenericControl)Master.Master.Master.FindControl("h2bottom");
if (dt.Rows[0]["H2Text"].ToString() == "")
{
h2.InnerText = "site general text";
}
else
{
h2.InnerText = this.CurrentEnsemble.Title + " " + dt.Rows[0]["H2Text"].ToString();
}
The error is thrown at
ad.Fill(dt)
I am not sure where I am making the mistake.
Thanks and appreciate it
Try adding with (nolock) statements to your statment. Similar problem here: SqlDataAdapter.Fill() Timeout - Underlying Sproc Returns Quickly

Categories

Resources