【问题标题】:save new record entered from Datagridview into the database将从 Datagridview 输入的新记录保存到数据库中
【发布时间】:2011-11-16 23:54:15
【问题描述】:

我正在使用 DataSet 和 TableAdapter 来填充 Datagridview。 Datagridview 允许在底部插入新记录。现在,当我在 Datagridview 中输入新记录的值时,该记录不会自动保存回数据库。你需要处理哪个事件或者我需要编写什么代码才能将新记录保存回数据库。

我正在使用 C#。

【问题讨论】:

  • 您是使用代码(如果是,请发布)还是使用数据源填充网格视图?
  • Windows 窗体还是 Web 窗体?能否展示用于将数据绑定到网格的代码?
  • 我用 TableAdapter 及其 Windows 窗体应用程序填充 DataGridView。

标签: winforms c#-4.0 datagridview dataset datatableadapters


【解决方案1】:

您可以在某处放置一个保存按钮,当用户单击该按钮时,您会调用如下方法:

private void UpdateDataSet(DataSet dataSet)
{
    // Check for changes with the HasChanges method first.
    if(!dataSet.HasChanges(DataRowState.Modified)) return;

    // Create temporary DataSet variable and
    // GetChanges for modified rows only.
    DataSet tempDataSet = 
        dataSet.GetChanges(DataRowState.Modified);

    // Check the DataSet for errors.
    if(tempDataSet.HasErrors)
    {
        // Insert code to resolve errors.
    }
    // After fixing errors, update the data source with  
    // the DataAdapter used to create the DataSet.
    adapter.Update(tempDataSet);
}

【讨论】:

    【解决方案2】:

    你是在TableAdapter 上调用Update() 方法吗?以下代码来自MSDN's discussion on the TableAdapter:

    try 
    {
        this.Validate();
        this.customersBindingSource.EndEdit();
    
        this.customersTableAdapter.Update(this.northwindDataSet.Customers);
        MessageBox.Show("Update successful"); 
    } 
    catch (System.Exception ex) 
    {
        MessageBox.Show("Update failed"); 
    }
    

    您可以在很多地方放置这种逻辑 - 正如 Davide Piras 建议的那样,您可以在表单上设置一个保存按钮,或者如果您希望在输入每一行时保存数据,您可以使用RowValidated 事件处理程序。

    【讨论】:

      猜你喜欢
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 1970-01-01
      • 2013-08-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多