10

I've had a look at this post How to programmatically insert a row in a GridView? but i can't get it to add a row i tried it on RowDataBound and then DataBound event but they both aren't working here is my code if someone could show me how to dynamically add a row to the end of GridView not Footer that would be cool anyway here is my code that doesn't work

protected void CustomGridView_DataBound(object sender, EventArgs e)
{
    int count = ((GridView)sender).Rows.Count;
    GridViewRow row = new GridViewRow(count+1, -1, DataControlRowType.DataRow, DataControlRowState.Insert);
    //lblCount.Text = count.ToString();
    // count is correct
    // row.Cells[0].Controls.Add(new Button { Text="Insert" });
    // Error Here adding Button 
    Table table = (Table)((GridView)sender).Rows[0].Parent;
    table.Rows.Add(row);
    // table doesn't add row          
}
3
  • In what event you want to add a row to the gridview ? Commented Jan 2, 2012 at 11:57
  • I want to add an insert row at the bottom not on the footer so I don't mind which event you use. I also need to add a button to the first column Commented Jan 2, 2012 at 12:02
  • Why are you avoiding using the footer? Commented Jan 2, 2012 at 17:53

1 Answer 1

10

Using the RowDataBound event, add any Control to a TableCell, and the TableCell to the GridViewRow. Finally add the GridViewRow to the GridView at a specified index:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    GridViewRow row = new GridViewRow(e.Row.RowIndex+1, -1, DataControlRowType.DataRow, DataControlRowState.Insert); 
    TableCell cell = new TableCell();
    cell.ColumnSpan = some_span;
    cell.HorizontalAlign = HorizontalAlign.Left;

    Control c = new Control(); // some control
    cell.Controls.Add(c);
    row.Cells.Add(cell);

    ((GridView)sender).Controls[0].Controls.AddAt(some_index, row);
} 

This may not be exactly how you need it but it should give you an idea.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.