强制从已过滤的DataGridView更新到数据库

时间:2015-06-16 19:29:06

标签: c# sql-server-2008

我创建了一个应用程序,用于在从计算机传输数据时修复日期转换问题。转换效果很好。我创建一个包含所有记录的DataGridView。然后我对DataGridView进行排序,以显示需要使用SqlDataAdapter和DataSet进行更新的数据。然后,我对DataGridView中的数据进行了更改,然后单击“保存”按钮将更改应用于数据库表。

     try
        {
            MessageBox.Show("Complete");
            this.log5DataGridView.EndEdit();
            //this.log5BindingSource.DataSource = this.log5DataGridView.DataSource; <-- Last Resort
            this.log5BindingSource.ResetBindings(false);
            this.log5BindingSource.EndEdit();
            this.log5TableAdapter.Update(roboticlineDataSet.Log5);
        }
        catch { }

当我在调试模式下运行时,log5DataGridView.DataSource表[]显示数据更改可用。但log5BindingSource似乎永远不会得到更改以将其推送到TableAdapter更新。我尝试了ResetBindings,EndEdit()最后一件事是拿数据源并强制它到BindingSource。

如果我使用以下代码搜索精确记录,则不会发生对数据库的保存/更新。

 using (SqlDataAdapter adpt = new SqlDataAdapter("SELECT * FROM [dbo].[RoboticLine] WHERE [FSItemNumber] = '" + Value + "' ORDER BY [FSItemNumber] ASC;", conn))
                        {
                            DataSet ds = new DataSet();
                            adpt.Fill(ds);
                            valueComboBox.Enabled = false;
                            log5DataGridView.DataSource = ds.Tables[0];
                            log5DataGridView.Refresh();
                            this.log5DataGridView.Rows[0].Selected = true;
                        }//end of adpt using

问题是,是否有办法将搜索到的log5DataGridView记录保存回数据库,因为datagridview表保留了更改,但log5BindingSource仍然包含原始

this.log5TableAdapter.Fill(this.roboticlineDataSet.Log5);

谢谢。

1 个答案:

答案 0 :(得分:0)

发现发生了什么,当我编写datagridview以显示搜索到的数据时,它没有更改绑定源,但是从Form Load()中保留了相同的内容。

this.log5TableAdapter.Fill(this.roboticlineDataSet.Log5);

为了解决这个问题,我在Soultion Explorer的Dataset.xsd位置找到了RoboticLineTable。在这里,我选择了roboticlinetableadapter并右键单击我选择Add-&gt; Query的位置。在这里,我创建了一个SQL查询,其中ID = @Value,以执行所需的过滤/搜索。这将使用此代码替换使用SqlDataAdapter代码

this.log5DataGridView.EndEdit();
this.log5BindingSource.EndEdit();    
this.log5tableAdapter.FillByID(this.roboticline.Log5, Value);
this.invalidate();
this.log5DatagridView.Refresh();

现在,当我希望保存时,BindingSource会在datagridview中进行更改并更新/保存到数据库。创建和重新填充tableadapter有助于保持链接到bindingsource。

希望这可以帮助将来可能遇到此问题的其他人