SqlDataAdapter.Update(数据表)不起作用(不更新数据库)

时间:2016-04-05 16:34:30

标签: c# winforms datagridview windows-applications sqldataadapter

我有以下代码,我试图从Windows应用程序中的c#网格视图更改中更新数据库....

代码未更新SQL Server数据库。我不确定问题究竟发生在哪里。一切似乎都很好......

或者有没有办法使用"更新查询语句更新数据库表"关键是如何为数据网格视图中的任何值更改编写update语句?

我认为绑定和select命令语句可能存在问题......

有人能指出我正确的方向来解决这个问题吗?

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");
        }
    }
}

1 个答案:

答案 0 :(得分:1)

试试这个:

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");

            }
          }
    }