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

时间:2019-04-26 18:29:04

标签: c# asp.net 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;
   }
}

如何防止隐藏这些字段?

1 个答案:

答案 0 :(得分: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;
    }
}