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

這可能不是正是你需要如何,但它應該給你一個想法。