Data.Tables数据入库问题(急)
数据库表格式:
填报年月 设备编号 设备名称 设备消耗 。。。。
填报年月 设备编号 是主键
this.Data.Tables[tableName]
绑定到UltraWebGrid
uwdSbyz.DataSource = this.Data.Tables[tableName].DefaultView;
uwdSbyz.DataBind();
下面是我的一个保存方法:
public static bool SaveWebGridDatasToDatabase(DataTable dt)
{
try
{
Database db = DatabaseFactory.CreateDatabase();
DbConnection connection = db.CreateConnection();
DbDataAdapter adapter = db.GetDataAdapter();
adapter.SelectCommand = db.DbProviderFactory.CreateCommand();
adapter.SelectCommand.Connection = connection;
adapter.SelectCommand.CommandText = "select * from " + dt.TableName;
DbCommandBuilder commandBuilder = db.DbProviderFactory.CreateCommandBuilder();
commandBuilder.DataAdapter = adapter;
adapter.InsertCommand = commandBuilder.GetInsertCommand();
adapter.UpdateCommand = commandBuilder.GetUpdateCommand();
adapter.DeleteCommand = commandBuilder.GetDeleteCommand();
adapter.InsertCommand.Connection = connection;
adapter.DeleteCommand.Connection = connection;
adapter.UpdateCommand.Connection = connection;
adapter.Update(dt);
return true;
}
catch
{
return false;
}
}
调用方法保存:
protected void btnSubmit_Click(object sender, Infragistics.WebUI.WebDataInput.ButtonEventArgs e)
{
try
{
this.uwdSbyz.RaisePostDataChangedEvent();
PublicDbWeb.SaveWebGridDatasToDatabase(this.Data.Tables[tableName]);
//接受所做的更改
this.Data.Tables["YT_SBYZ"].AcceptChanges();
if (this.Data.HasErrors)
{
PrintRowErrs(this.Data);
this.Data.RejectChanges();
uwdSbyz.DataSource = this.Data.Tables[tableName].DefaultView;
uwdSbyz.DataBind();
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "click", "alert('数据保存失败!')", true);
}
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "click", "alert('数据已成功保存!')", true);
}
catch (Exception updateError)
{
Console.Write(updateError.StackTrace);
this.Data.RejectChanges();
uwdSbyz.DataSource = this.Data.Tables[tableName].DefaultView;
uwdSbyz.DataBind();
ScriptManager.RegisterClientScriptBlock(this.UpdatePanel1, this.GetType(), "click", "alert('数据保存失败!')", true);
}
}
以上代码使用于从库里取书库绑定到UltraWebGrid后,更改,删除,插入。
设备信息每月要提交一次,设备编号,设备名称等基本信息是不变的,从上月记录中提取到this.Data.Tables[tableName]后,对“填报年月”列赋值为 本月月份。然后再绑定到UltraWebGrid,在UltraWebGrid对 设备消耗 等数据进行填写(并更改到Tables),现在要把这个新的Tables的内容插到数据库,上面的保存方法不行,因为更改了主键,引发错误“违反并发性: UpdateCommand 影响了预期 1 条记录中的 0 条。”
求把新 Tables插到数据库的方法!