2012-01-02 43 views
8

我看过这篇文章How to programmatically insert a row in a GridView?,但我不能得到它添加一行我在RowDataBound然后DataBound事件尝试它,但他们都没有在这里工作是我的代码如果有人能告诉我如何动态地将行添加到GridView控件不页脚的结束,这将是很酷反正这里是我的代码不能正常工作asp.net动态添加GridViewRow

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   
} 
+0

在什么事件中你想添加一行到gridview? – Bibhu 2012-01-02 11:57:14

+0

我想在底部添加一个插入行而不是在页脚上,所以我不介意使用哪个事件。我还需要在第一列添加一个按钮 – ONYX 2012-01-02 12:02:58

+0

为什么你要避免使用页脚? – 2012-01-02 17:53:54

回答

9

使用RowDataBound事件,任何控件添加到的TableCell ,并将TableCell添加到GridViewRow。最后,GridViewRow添加到GridView指定索引处:

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

这可能不是正是你需要如何,但它应该给你一个想法。