动态设置Gridview的标题行文本

本文关键字:文本 标题 设置 Gridview 动态 | 更新日期: 2023-09-27 18:13:54

嗨,伙计们,我有这个函数动态创建gridviews并将其添加到页面。数据源也是使用数据表动态设置的。我想将标题行文本设置为数据表的tablename。

private void AddGridview(DataTable dt)
{
    if (dt.Rows.Count > 0)
    {
        GridView gridView = new GridView();
        gridView.CssClass = "gridview";
        gridView.DataSource = dt;
        gridView.AutoGenerateColumns = false;
        gridView.ShowHeader = true;
        gridView.HeaderRow.Cells[0].Text = dt.TableName;
        remittance.Controls.Add(gridView);
    }
}

在第39行抛出以下错误:

Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error: 
Line 37:             gridView.AutoGenerateColumns = false;
Line 38:             gridView.ShowHeader = true;
Line 39:             gridView.HeaderRow.Cells[0].Text = dt.TableName;
Line 40:             remittance.Controls.Add(gridView);
Line 41:         } 

有什么办法吗?

动态设置Gridview的标题行文本

代替

gridView.HeaderRow.Cells[0].Text = dt.TableName;

使用这个

gridView.Columns[0].HeaderText = dt.TableName;
更新:

private void AddGridview(DataTable dt)
{
    if (dt.Rows.Count > 0) {
        GridView gridView = new GridView();
        gridView.CssClass = "gridview";
        gridView.DataSource = dt;
        gridView.DataBind();
        gridView.AutoGenerateColumns = false;
        gridView.HeaderRow.Visible = false;
        Table table = gridView.Controls(0);
        GridViewRow gvRow = new GridViewRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
        TableCell newCell = new TableCell();
        newCell.ColumnSpan = dt.Columns.Count - 1;
        newCell.Text = dt.TableName;
        gvRow.Cells.Add(newCell);
        table.Rows.AddAt(0, gvRow);
        remittance.Controls.Add(gridView);
    }
}

你需要先添加列

    foreach(var col in table.Columns)
      gridview1.Columns.add(table.ColumnName);