我知道这是DataGridView的基本功能,但由于某种原因,我无法让它工作。我只希望Windows窗体上的DataGridView在用户单击“保存”按钮时向数据库提交对其进行的任何更改。
我根据DropDownList中用户选择触发的函数填充DataGridView,如下所示:
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife], rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife], rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix] FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con);
DataSet ruleTableDS = new DataSet();
ruleTableDA.Fill(ruleTableDS);
RuleTable.DataSource = ruleTableDS.Tables[0];
}
在我的保存功能中,我基本上有以下内容(我已经修剪了一些代码以便达到目的):
using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife],
rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
DataTable dt = new DataTable();
dt = RuleTable.DataSource as DataTable;
ruleTableDA.Fill(dt);
ruleTableDA.Update(dt);
}
好的,所以我编辑了代码来执行以下操作:构建命令,基于DataGridView(RuleTable)创建DataTable,使用DataTable填充DataAdapter,并更新数据库。现在ruleTableDA.Update(dt)抛出异常“并发冲突:UpdateCommand影响了预期的1条记录中的0条。”
答案 0 :(得分:5)
我相信这里有一些问题: 要记住的顺序是,当您加载网格时,它已经指向数据表/集合。 键入网格时,更改会暂时保留到绑定到网格的数据表中。因此,您不希望每次保存时都创建数据表,因为忽略了对现有数据表所做的更改。 第二个问题是你可能不需要每次都创建一个绑定源,因为就像第一点一样,如果网格显示数据,那么它已经绑定了绑定源。 第三个问题是SQLCommandBuilder类具有GetInsertCommand,GetUpdateCommand等方法,必须使用它们来实际获取相应的命令。
using (SqlDataAdapter ruleTableDA = new SqlDataAdapter("SELECT rule.fldFluteType AS [Flute], rule.fldKnife AS [Knife],
rule.fldScore AS [Score], rule.fldLowKnife AS [Low Knife],
rule.fldMatrixScore AS [Matrix Score], rule.fldMatrix AS [Matrix]
FROM dbo.tblRuleTypes rule WHERE rule.fldMachine_ID = '1003'", con))
{
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(ruleTableDA);
DataTable dt = new DataTable();
dt = RuleTable.DataSource as DataTable;
//ruleTableDA.Fill(dt);
ruleTableDA.Update(dt);
}
答案 1 :(得分:2)
MSDN文档指出在手动设置SelectCommand时会自动设置update / delete / insert命令。它没有提到当你使用SqlDataAdapter构造一个时它也会这样做。尝试在创建SqlCommanduBuilder后添加这些行。
ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand()
ruleTableDA.InsertCommand = commandBuilder.GetInsertCommand()
ruleTableDA.DeleteCommand = commandBuilder.GetDeleteCommand()
答案 2 :(得分:0)
您可能需要这样才能获得更新命令
ruleTableDA.UpdateCommand = commandBuilder.GetUpdateCommand();