使用DataBound事件隐藏Gridview中的空列

问题描述 投票:0回答:1

我正在使用以下内容在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;
   }
}

如何防止这些字段被隐藏?

c# asp.net gridview
1个回答
1
投票

检查列类型:

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.