2016-04-05 15 views
0

我有这样的代码,我正在尝试更新从Windows应用程序进行的C#gridview的变化的数据库....什么数据适配器命令应该用来通过gridview在c#Winforms更新数据库表?

在更新按钮单击事件宣告适配器选择命令时出现问题...

我不知道该选择命令或使用,使得它在更新数据库表中的datagridview的变化更新命令....

任何人都可以点我在正确的方向来解决这个问题?

public partial class KnowledgeBaseForm : Form 
{ 
    private SqlDataAdapter SDA = new SqlDataAdapter(); 

    private void button_retrievekb_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      con.Open(); 
      SqlDataAdapter SDA = new SqlDataAdapter(@"SELECT * From Table1", con); 

      DT = new DataTable(); 
      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; 
     SDA.SelectCommand = (//some necessary command or NULL update command which needs to update my database); 

     scb = new SqlCommandBuilder(SDA);     
     SDA.Update((DataTable) bindingsource.DataSource); 
     MessageBox.Show("Updates successfully submitted to CoSD"); 
    } 
} 

回答

0

您可能需要考虑更新电网的DataSource财产后的任何更改了与之相关的数据源(如bindingSource)制成。

也许下面的内容类似:

SDA.Update((DataTable) bindingsource.DataSource); 
// After updating everything, rebind your grid 
dataGridView.DataSource = bindingsource.DataSource; 
+0

感谢输入......但是当我试图调用methiod datagridview.DataBind()......它抛出一个错误“'System.Windows.Forms的.DataGridView'不包含'DataBind'的定义...“这个方法是一个内置的方法还是我需要创建一个? –

+0

其实没有那个正确的。 'DataBind()'在Web窗体中使用,而不是WinForms。这个问题可能与在Update调用中没有为你的Grid设置/更新'DataSource'有关。 –

+0

bindingsource.DataSource = dataGridView.DataSource; ......语句从gridview中获取更新的数据....我在调试时检查了它....问题出现在“选择更新按钮的commnad点击“......你对这一个有什么看法...... –