--------------------------------------------------------------------------------
Hi, I am really having a problem with trying to get my datagrid to update my data base.
I have tried 2 different sets of codes, but when ever I enter the new data to be updated and click update, the datagrid will just return to the orginal datas. There is no updating done. I really am very new to this. Please advice what are the problems in my code that I must change. Thanks.
i use visual studio.net to write this codes.
First try:
Code:
public void SqlCmdConn(string sqlCmd)
{
//First openning the connection to the db
SqlConnection conn = new SqlConnection("Initial Catalog=Boomerang; Server=(local); UID=sa; PWD=; ");
SqlCommand cmd = new SqlCommand(sqlCmd,conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
public void updateRecords(object Sender, DataGridCommandEventArgs e)
{
int custid1 = Convert.ToInt32(e.Item.Cells[2].Text);
TextBox titleTB = (TextBox)e.Item.Cells[3].Controls[0];
String title1 = Convert.ToString(titleTB.Text);
String strSql = "UPDATE customer_reg SET title ='" +title1+ "'WHERE custid = "+custid1+"";
SqlCmdConn sCC = new SqlCmdConn(strSql);
DataGrid1.EditItemIndex = -1;
DataGrid1.DataBind();
}
Second try
Code:
public void updateRecords(object Sender, DataGridCommandEventArgs e)
{
//Retrive the primary key(column) for the row to be edited.
int custid = Convert.ToInt16(e.Item.Cells[2].Text);
//Enable editing for the 1 column
TextBox titleTB = (TextBox)e.Item.Cells[3].Controls[0];
string title = Convert.ToString(titleTB.Text);
DataGrid1.EditItemIndex = -1;
UpdateTitle(custid, title);
DataSet ds = new DataSet();
DataGrid1.DataSource = ds.Tables["customer_reg"];
DataGrid1.DataBind();
}
private void UpdateTitle(int custid, string title)
{
// Create and load a DataSet with records from BoomerandExt.customer_reg table
conn.Open();
String strConnection = "Initial Catalog=Boomerang; Server=(local); UID=sa; PWD=;";
String strSQLSelect = "SELECT * FROM customer_reg";
//string conn1 = "Initial Catalog=Boomerang; Server=(local); UID=sa; PWD=;";
//string cmd1 = "SELECT * FROM customer_reg";
SqlDataAdapter adapter = new SqlDataAdapter(strSQLSelect, strConnection);
DataSet ds = new DataSet();
adapt.Fill(ds, "customer_reg");
conn.Close();
// Modify the in-memory records in the DataSet
DataTable tbl = ds.Tables["customer_reg"];
tbl.PrimaryKey = new DataColumn[] {tbl.Columns["custid"]};
DataRow row = tbl.Rows.Find(custid);
row["title"] = title;
// Reconnect the DataSet and update the database
SqlCommandBuilder cb = new SqlCommandBuilder(adapt);
conn.Open();
adapt.Update(ds, "customer_reg");
conn.Close();
}