2012-04-18 104 views
0

我在我的项目中有一个场景我有一个网格视图和提交按钮,它会生成动态行,并且有一个图像按钮Edit它编辑这些行,并且这些行首先绑定数据表,当我们点击保存按钮全部反映在数据表中所做的更改保存在数据库中没有Update按钮从gridview更新datatable

问:

我如何能在以前编辑的行保存到DataTable并在其中活动吗?

plz帮助您的LinkBut​​ton其迫切

回答

0

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

 

    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(); 
    } 

0

放一个的CommandName和CommandArgument,并把你的代码保存在ItemCommand()为GridView控件应该工作。 哦,命令名称应该像“更新”,参数可以是该行的ID。

+0

我想这不是那么紧迫...... – 2012-04-18 10:54:12