我的项目中有一个场景我有一个生成动态行的网格视图和提交按钮,还有一个图像按钮Edit可以编辑这些行,这些行首先与数据表绑定,当我们点击保存按钮时,所有反映数据表保存中的更改在数据库中没有Update按钮
问题:
如何将先前编辑的行保存到DataTable事件中?
请帮助其紧急
将 CommandName 和 CommandArgument 放在您的 linkButton 上,并将您的保存代码放在 ItemCommand() 中,这样 GridView 应该可以工作。哦,命令名称应该类似于“更新”,并且参数可以是该行的 Id。
声明一个数据表,向其中添加列以表示我要从网格保存到数据库中的表的所有数据。遍历网格中的行,从要保存的每个单元格中获取数据并将其添加到数据表中的每一列。使用数据表对数据库中的表进行批量插入。
数据表 dtMealTemplate = new DataTable();
dtMealTemplate.Columns.Add("MealTemplateID", Type.GetType("System.Int32"));
dtMealTemplate.Columns.Add("WeekNumber", Type.GetType("System.Int32"));
dtMealTemplate.Columns.Add("DayOfWeek", Type.GetType("System.String"));
foreach(GridView.Rows 中的 GridViewRow gvr)
{
drMT = dtMealTemplate.NewRow();
drMT["MealTemplateID"] = gvr.Cells[0].text;
drMT["WeekNumber"] = gvr.Cells[1].text;
drMT["DayOfWeek"] = gvr.Cells[2].Text;
dtMealTemplate.Rows.Add(drMT);
}
公共无效InsertMealsTemplate(int iMealTemplateID,DataTable dtMealsData)
{
SqlCommand cmd = 新的 SqlCommand();
SqlDataAdapter sa = new SqlDataAdapter(cmd);
SqlCommandBuilder cmb = new SqlCommandBuilder(sa);
SqlTransaction oTrans;
SqlConnection oConn = new SqlConnection(GetConnectionString());
数据集 ds = new DataSet();
oConn.Open();
cmd = oConn.CreateCommand();
oTrans = oConn.BeginTransaction();
cmd.Connection = oConn;
cmd.Transaction = oTrans;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM YOURTABLENAME WHERE 1 = 1";
sa = 新的 SqlDataAdapter(cmd);
cmb = new SqlCommandBuilder(sa);
sa.MissingSchemaAction = MissingSchemaAction.AddWithKey;
cmd.Transaction = oTrans;
sa.Fill(ds, "yourtablename");
数据行 drNew;
诠释 x = 0;
foreach(dtMealsData.Rows 中的 DataRow dr)
{
if (Int32.Parse(dr["MealDetailsID"].ToString()) == 0)
{
drNew = ds.Tables[0].NewRow();
drNew["MealTemplateID"] = dr["MealTemplateID"];
drNew["WeekNumber"] = dr["WeekNumber"];
drNew["DayOfWeek"] = 博士["DayOfWeek"];
ds.Tables[0].Rows.Add(drNew);
}
}
sa.Update(ds.Tables["yourtablename"]);
oTrans.Commit();
oConn.Close();
}