动态设置Gridview的标题行文本

时间:2011-11-09 22:06:14

标签: c# asp.net gridview

大家好我有这个功能,动态创建gridviews并将其添加到页面。 使用数据表动态设置数据源。我想将标题行文本设置为数据表的表名。但以下情况不起作用:

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:         } 

任何想法如何做到这一点?

提前致谢。

2 个答案:

答案 0 :(得分:3)

而不是

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

答案 1 :(得分:0)

您需要先添加列

    foreach(var col in table.Columns)
      gridview1.Columns.add(table.ColumnName);
相关问题