asp.net动态添加GridViewRow

时间:2012-01-02 11:48:30

标签: c# webforms

我已经看过这篇文章How to programmatically insert a row in a GridView?但是我无法在RowDataBound上添加一行我尝试它然后DataBound事件但它们都不能在这里工作是我的代码,如果有人可以告诉我如何动态添加一行到GridView而不是Footer的末尾,无论如何这将是我的代码不能正常工作

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          
}

1 个答案:

答案 0 :(得分:9)

使用RowDataBound事件,将任何Control添加到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);
} 

这可能不完全是你需要的,但它应该给你一个想法。