如何在asp.net中以编程方式编辑gridview?

时间:2013-10-10 07:35:48

标签: asp.net c#-4.0 gridview dynamic edit

  GridView gv = new GridView();

  BoundField farmername = new BoundField();
  farmername.HeaderText = "Farmer Name";
  farmername.DataField = "farmername";
  gv.Columns.Add(farmername);


  BoundField villagename = new BoundField();
  villagename.HeaderText = "Village Name";
 villagename.DataField = "village";
 gv.Columns.Add(villagename);

  BoundField feedtype = new BoundField();
  feedtype.HeaderText = "Feed Type";
  feedtype.DataField = "feedtype";
  gv.Columns.Add(feedtype);


  BoundField bf50kg = new BoundField();
  bf50kg.HeaderText = "50 Kg Bags";  
  bf50kg.DataField = "noof50kgsbags";
  gv.Columns.Add(bf50kg);

  CommandField cf = new CommandField();
  cf.ButtonType = ButtonType.Button;
  cf.ShowCancelButton = true;
  cf.ShowEditButton = true;
  gv.Columns.Add(cf);

  gv.RowEditing += new GridViewEditEventHandler(gv_RowEditing);
  gv.RowUpdating += new GridViewUpdateEventHandler(gv_RowUpdating);
  gv.RowCancelingEdit += new GridViewCancelEditEventHandler(gv_RowCancelingEdit);

  gv.AutoGenerateColumns = false;
  gv.ShowFooter = true;
  gv.DataSource = dtIndentDetails;
  gv.DataBind();

当我点击编辑按钮时,它不会分成更新,取消按钮。如何使用命令字段执行此操作。如果我在aspx页面中添加gridview,则将其拆分为更新和取消

2 个答案:

答案 0 :(得分:1)

请尝试以下代码:

protected void gridview_RowEditing(object sender, GridViewEditEventArgs e)
{
    GridView gv = (GridView)sender;
   // Change the row state
    gv.Rows[e.NewEditIndex].RowState = DataControlRowState.Edit;

}

答案 1 :(得分:1)

尝试了您的代码,发现它正常运行。 请注意以下几点:

1。)每次都应该执行创建GridView(以及所有字段)的代码。意味着从此代码中删除任何!IsPostback条件,如果存在的话。

2。)在gridview的RowEditing事件中设置editindex并重新绑定gridview。

protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView gv = sender as GridView;
        gv.EditIndex = e.NewEditIndex;
        gv.DataBind();
    }