Gowtham Ramamoorthy Gowtham Ramamoorthy - 3 months ago 30
C# Question

sql adapter.update (data table) is not working (Not updating the database)

I have the below code where I'm trying to update a database from the c# grid view change made in windows application....

The code is not updating the database in the sql server....I'm not sure where exactly the issue occurs.. everyhting seems to be fine...

or is there a way to update the database table usig the "update querey statement" again the point is how to write the udate statement for any value changes in the data grid view ?

I presume there might be an issue with binding and the select command statements...

Could anyone point me in the right direction to solve this issue ?

public partial class KnowledgeBaseForm : Form
{
private SqlDataAdapter SDA = new SqlDataAdapter();
private DataTable DT = new DataTable();
private void button_retrievekb_Click(object sender, EventArgs e)
{
try
{
con.Open();
SqlDataAdapter SDA = new SqlDataAdapter(@"SELECT * From Table1", con);



SDA.Fill(DT);
bindingsource.DataSource = DT;
dataGridView.DataSource = bindingsource;
if (DT.Rows.Count > 0)
{


dataGridView.Columns[0].DefaultCellStyle.ForeColor = Color.Gray;
dataGridView.Columns[0].ReadOnly = true;

}
else
{
MessageBox.Show("No Knowledge Base Rules Found");


}

}


catch (Exception ex)
{
MessageBox.Show("Error : " + ex.Message);
}

finally
{
con.Close();
}

}



private void button_update_Click(object sender, EventArgs e)
{


if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
//binding the datasource with the changes made in the gridview
bindingsource.DataSource = dataGridView.DataSource;
DT.AcceptChanges();
scb = new SqlCommandBuilder(SDA);
SDA.Update((DataTable) bindingsource.DataSource);
MessageBox.Show("Updates successfully submitted to CoSD");

}


}

Answer

Try this:

public partial class KnowledgeBaseForm : Form
    {
     SqlDataAdapter SDA = new SqlDataAdapter();
     DataTable DT = new DataTable();
     DataSet ds = new DataSet();
    private void button_retrievekb_Click(object sender, EventArgs e)
            {

               SDA = new SqlDataAdapter(@"SELECT * From Table1", con);
               ds = new DataSet();
               SDA.fill(ds,"SomeName");
               dataGridView1.DataSource = ds.Tables[0];
            }

    private void button_update_Click(object sender, EventArgs e)
          {


            if (MessageBox.Show("Do you really want to Update these values?", "Confirm Update", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
               SqlCommandBuilder builder = new SqlCommandBuilder(SDA);
               SDA.Update(ds,"SomeNme");

            }
          }
    }
Comments