ASP.NET Gridview - 代码中的动态 - 非空数据 table 作为源 - DataBind 抛出异常

ASP.NET Gridview - Dynamic in code - non-null data table as Source - DataBind throws Exception

C#ASP.Net4.7.2

我正在基于传入的数据集在代码中创建一个 Gridview。我即时创建 BoundFields,然后分配 DataSource 并尝试进行 DataBind。此代码位于单独的 class 中。我将页面中的占位符传递给它。

代码如下:

    DGWorkWith = new GridView()
    {
        AllowPaging = true,
        AllowSorting = true,
        PageSize = 50,
        AutoGenerateColumns = false,
        BorderColor = Color.Black,
        BorderWidth = 1
    };
    DataSet wwDS = LoadDataSet(_sDB,_sPW);
    DataTable wwDT = wwDS.Tables[0];
    foreach (DataColumn DC in wwDT.Columns)
    {
        string sColName = DC.ColumnName.ToUpper().Trim();
        string sWidth = myRM.GetString(sColName + "_WIDTH");
        if (sWidth == null) { sWidth = "120"; }
        int iWidth = Convert.ToInt32(sWidth);
        //if (IsFieldChooserColumnOn(sColName)) { continue; }
        // Put DataColumn in List
        string sColHdr = "";
        if (myRM.GetString(sColName) == null)
        {
            sColHdr = "???-" + DC.ColumnName.ToUpper().Trim();
        }
        else
        {
            sColHdr = myRM.GetString(sColName);
        }

        BoundField BC = new BoundField();
        BC.DataField = DC.ColumnName.Trim();
        BC.HeaderText = sColHdr;
        if(iWidth==0) { BC.Visible = false;  }
        DGWorkWith.Columns.Add(BC);
    }
    DGWorkWith.DataSource = wwDT;
    // *** THIS DATABIND FAILS with an Object reference not set to an instance of an object.
    DGWorkWith.DataBind();
    TR2TC2.Controls.Add(DGWorkWith);
    
    TR2.Cells.Add(TR2TC2);
    T.Rows.Add(TR2);
    placeHolder.Controls.Add(T); //T is a Table and the placeholder is fed the table.

DataBind 调用失败,出现空对象引用异常。

我一头雾水

有人看到我遗漏的东西吗?

谢谢! 约翰.

我发现了问题。它在这段代码中:

TR2TC2.Controls.Add(DGWorkWith);

TR2.Cells.Add(TR2TC2);
T.Rows.Add(TR2);
placeHolder.Controls.Add(T); //T is a Table and the placeholder is fed the table.

问题是我在尝试 DataBind 之前我将 GridView 附加到任何控件。显然,动态 GridView 必须是页面某处的控件在数据绑定之前

哇哦。

Microsoft 非常擅长 记录此类内容。