Sambasiva
Sambasiva

Reputation: 1044

how to edit the gridview programatically in asp.net?

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

When I clicked on edit button its not spliting into update, Cancel buttons . How can I do this with command field .If I add gridview in aspx page, its splitting to update and cancel

Upvotes: 2

Views: 2360

Answers (2)

R.C
R.C

Reputation: 10565

Tried your code and found it working. Take care of below points:

1.) The Code creating GridView (and all fields ) should be executed every time. Means remove any !IsPostback condition from this code, If present any.

2.) In your RowEditing event of your gridview set the editindex and rebind the gridview.

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

Upvotes: 1

milan m
milan m

Reputation: 2244

Try the following code:

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

}

Upvotes: 1

Related Questions