C# 从gridview更新datatable

C# 从gridview更新datatable,c#,asp.net,C#,Asp.net,我在我的项目中有一个场景,我有一个网格视图和提交按钮,它生成动态行,还有一个图像按钮编辑这些行,这些行首先与datatable绑定,当我们单击save按钮时,所有反映datatable中的更改save in database没有更新按钮 问题: 如何将以前编辑的行保存到DataTable中?在哪种情况下 Plz帮助它的紧急功能将CommandName和CommandArgument放在链接按钮上,并将保存代码放在ItemCommand中,以便GridView可以工作。 哦,命令名应该类似于Upd

我在我的项目中有一个场景,我有一个网格视图和提交按钮,它生成动态行,还有一个图像按钮编辑这些行,这些行首先与datatable绑定,当我们单击save按钮时,所有反映datatable中的更改save in database没有更新按钮

问题:

如何将以前编辑的行保存到DataTable中?在哪种情况下


Plz帮助它的紧急功能

将CommandName和CommandArgument放在链接按钮上,并将保存代码放在ItemCommand中,以便GridView可以工作。
哦,命令名应该类似于Update,参数可以是该行的Id。

声明一个datatable,向其中添加列,以表示我要从网格保存到DB中表中的所有数据。 循环遍历网格中的行,从要保存的每个单元格中获取数据,并将其添加到datatable中的每列。 使用datatable对数据库中的表进行大容量插入

DataTable 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 (GridViewRow gvr in GridView.Rows) { 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); } public void InsertMealsTemplate(int iMealTemplateID, DataTable dtMealsData) { SqlCommand cmd = new SqlCommand(); SqlDataAdapter sa = new SqlDataAdapter(cmd); SqlCommandBuilder cmb = new SqlCommandBuilder(sa); SqlTransaction oTrans; SqlConnection oConn = new SqlConnection(GetConnectionString()); DataSet 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 = new SqlDataAdapter(cmd); cmb = new SqlCommandBuilder(sa); sa.MissingSchemaAction = MissingSchemaAction.AddWithKey; cmd.Transaction = oTrans; sa.Fill(ds, "yourtablename"); DataRow drNew; int x = 0; foreach (DataRow dr in dtMealsData.Rows) { if (Int32.Parse(dr["MealDetailsID"].ToString()) == 0) { drNew = ds.Tables[0].NewRow(); drNew["MealTemplateID"] = dr["MealTemplateID"]; drNew["WeekNumber"] = dr["WeekNumber"]; drNew["DayOfWeek"] = dr["DayOfWeek"]; ds.Tables[0].Rows.Add(drNew); } } sa.Update(ds.Tables["yourtablename"]); oTrans.Commit(); oConn.Close(); }