Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net dynamically add GridViewRow

Tags:

c#

webforms

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          
}
like image 822
ONYX Avatar asked Jan 02 '12 11:01

ONYX


1 Answers

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.

like image 168
Brissles Avatar answered Oct 14 '22 07:10

Brissles