Search code examples
c#asp.netgridviewboundfield

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


C# ASP.Net 4.7.2

I am creating a Gridview in code based on the dataSet passed in. I create the BoundFields on the fly, and then I assign the DataSource and attempt a DataBind. This code is in a separate class. to which I pass in a placeholder from a page.

Here is the code:

    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.

The DataBind call fails with the null object reference exception.

  • DGWorkWith is not Null
  • The columns are all present for every data column in the DataTable
  • The column names in the BoundFields match the ColumnNames in the DataTable.
  • There are rows in the DataTable -- over 12000 of them.
  • Attempting to step into the DataBind throws the exception at once.

I am completely perplexed.

Does anyone see something I have missed?

Thanks! John.


Solution

  • I found the problem. It was in this code here:

    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.
    

    The problem is that I was attempting the DataBind before I had attached the GridView to any control. Apparently, a dynamic GridView must be a control somewhere on the page prior to data binding.

    Wow.

    Microsoft is so good at documenting things like this.