【发布时间】:2021-01-12 05:55:55
【问题描述】:
C# ASP.Net 4.7.2
我正在根据传入的数据集在代码中创建一个 Gridview。我动态创建 BoundField,然后分配 DataSource 并尝试 DataBind。此代码在一个单独的类中。我从一个页面传入一个占位符。
代码如下:
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 调用失败,出现空对象引用异常。
- DGWorkWith 不是 Null
- DataTable 中的每个数据列都存在这些列
- BoundFields 中的列名与 数据表。
- DataTable 中有行 -- 超过 12000 行。
- 尝试进入 DataBind 会立即引发异常。
我完全糊涂了。
有人看到我错过的东西吗?
谢谢! 约翰。
【问题讨论】:
-
无论我尝试什么,代码都有效。我无法重现该问题...您确定问题不在其他地方,因为您可以将 null 绑定到 GridView(
DGWorkWith.DataSource = null;显示一个空的 GridView) -
我可以将 null 绑定到 gridview,它只显示 DataTable 之外什么都没有。 -- 它有列和行,并且每个列名都与 dataTable 中的列名匹配。
标签: c# asp.net gridview boundfield