c# - 使用 DataBound 事件在 Gridview 中隐藏空列
问题描述
我正在使用以下内容在我的 Gridview 中隐藏带有 DataBound 事件的空列。它适用于 BoundField 列,但即使存在数据,也会隐藏其他类型,例如 TemplateFields 和 HyperLinkFields。
protected void MyTable_DataBound(object sender, EventArgs e)
{
Boolean hasData = false;
for (int col = 0; col < MyTable.HeaderRow.Cells.Count; col++)
{
for (int row = 0; row < MyTable.Rows.Count; row++)
{
if(!String.IsNullOrEmpty(MyTable.Rows[row].Cells[col].Text)
&& !String.IsNullOrEmpty(HttpUtility.HtmlDecode(MyTable.Rows[row].Cells[col].Text).Trim()))
{
hasData = true;
break;
}
}
if (!hasData)
{
MyTable.HeaderRow.Cells[col].Visible = false;
for(int hiddenrows = 0; hiddenrows < MyTable.Rows.Count; hiddenrows++)
{
MyTable.Rows[hiddenrows].Cells[col].Visible = false;
}
}
hasData = false;
}
}
如何防止这些字段被隐藏?
解决方案
检查列类型:
protected void MyTable_DataBound(object sender, EventArgs e)
{
Boolean hasData = false;
for (int col = 0; col < MyTable.HeaderRow.Cells.Count; col++)
{
if (MyTable.Columns[col] is HyperLinkField || MyTable.Columns[col] is TemplateField)
{
continue;
}
for (int row = 0; row < MyTable.Rows.Count; row++)
{
if(!String.IsNullOrEmpty(MyTable.Rows[row].Cells[col].Text) && !String.IsNullOrEmpty(HttpUtility.HtmlDecode(MyTable.Rows[row].Cells[col].Text).Trim()))
{
hasData = true;
break;
}
}
if (!hasData)
{
MyTable.HeaderRow.Cells[col].Visible = false;
for(int hiddenrows = 0; hiddenrows < MyTable.Rows.Count; hiddenrows++)
{
MyTable.Rows[hiddenrows].Cells[col].Visible = false;
}
}
hasData = false;
}
}
推荐阅读
- ios - 何时布局 UIViewControllers 视图的子视图?
- vue.js - 在 vuetify 中使用 @submit 指令时,console.log 不起作用
- mysql - 如何使用领先或滞后在mysql中的给定行中获取上一行或下一行?
- sql-server - Tsql 是一种无需使用 sys.path 即可查找空表的方法。分区
- python - wxPython Phoenix中的渐变文本
- reactjs - 预检响应中的 Access-Control-Allow-Headers 不允许 Sails.js 请求标头字段授权
- webpack - Webpack 4 splitChunks all + multi-configuration 导致无法在 ./webpack/bootstrap 读取未定义的属性“调用”
- angular - 尝试使用 Angular TestBed 时出现奇怪的 RxJS 错误
- laravel - Intervention\Image\Exception\NotWritableException: Can't write image data to path Image\Image.php on line 143
- visual-studio - 即使已登录,Visual Studio 也会不断要求选择 Azure 帐户