【问题标题】:asp.net dynamically add GridViewRowasp.net 动态添加 GridViewRow
【发布时间】:2012-01-02 11:48:30
【问题描述】:

我看过这篇帖子How to programmatically insert a row in a GridView?,但我无法让它添加一行我在 RowDataBound 和 DataBound 事件上尝试过,但如果有人可以显示,它们都不能在这里工作是我的代码我如何动态地将一行添加到 GridView 的末尾而不是页脚,这无论如何都会很酷这是我的代码不起作用

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          
}

【问题讨论】:

  • 在什么情况下你想在 gridview 中添加一行?
  • 我想在底部而不是在页脚添加一个插入行,所以我不介意您使用哪个事件。我还需要在第一列添加一个按钮
  • 为什么要避免使用页脚?

标签: c# webforms


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-19
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 2013-09-11
    相关资源
    最近更新 更多