65.9K
CodeProject 正在变化。 阅读更多。
Home

通过HeaderText隐藏DataGrid列

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.50/5 (18投票s)

2005 年 7 月 20 日

2分钟阅读

viewsIcon

215015

downloadIcon

1414

展示了开发者如何动态隐藏或显示 DataGrid 列。

引言

许多 ASP.NET 应用程序都使用 DataGrid 控件。该控件能够通过使用 DataGridColumnsCollection 中包含的列的索引来动态隐藏或显示 DataGridColumn。例如,如果您想要隐藏网格中的第一列,您可以通过 DataGrid.Columns[0].Visible = false; 来实现。我使用列索引遇到的问题是当列需要重新排序时。这可能是一场噩梦,特别是当您的网格中有很多列时。想象一个包含 20 多个列的网格,您需要将第 11th 列移动到第 5th 个位置,并将第 20th 列移动到第 2nd 个位置,依此类推。每次这样做,您都需要修改代码中的列索引引用。

我心想,“必须有一种方法可以通过名称检索列”。好吧,没有可用的 DataGrid.Columns["Name"] 属性,但是有 Column.HeaderText。即使您决定不显示标头,如果您设置了 HeaderText 值,它仍然可用。要访问代码隐藏中的 HeaderText,只需循环遍历 DataGrid 列并检查 HeaderText

代码

下面是一个动态隐藏和显示列的方法示例。在我的示例解决方案中,我在将 DataTable 绑定到网格后调用 HideShowColumns

private void HideShowColumns(DataGrid dg)
{
    if(dg == null)
    {
        return;
    }
    // Loop through all of the columns in the grid.
    foreach(DataGridColumn col in dg.Columns)
    {
        // Are we in UserView Mode?
        if(this.lblUiView.Text == UserView.User.ToString())
        {
            // Hide the Salary and SS# Columns.
            if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
            {
                col.Visible = false;
            }
        }
        // Are we in AdminView Mode?
        else if(this.lblUiView.Text == UserView.Admin.ToString())
        {
            // Show the Salary and SS# Columns.
            if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
            {
                col.Visible = true;
            }
        }
    }
}

下面是 HideShowColumns 的一个更简单的版本。我删除了与我的示例解决方案相关的代码,以便您可以清楚地看到该示例。正如你所看到的,这是一个非常简单的解决方案。以下代码将隐藏 HeaderText 为“ExampleColumn”的列。

private void HideShowColumns(DataGrid dg)
{
    if(dg == null)
    {
        return;
    }
    // Loop through all of the columns in the grid.
    foreach(DataGridColumn col in dg.Columns)
    {
        // Hide the Salary and SS# Columns.
        if(col.HeaderText == "ExampleColumn")
        {
            col.Visible = false;
        }
    }
}

DataGrid 的 HTML

在我的示例中,我为 HTML 中的每一列添加了 HeaderText。您也可以在 WebPage 的代码隐藏类中设置此值。

<asp:datagrid id=dgExample AutoGenerateColumns="False" runat="server">
 <ALTERNATINGITEMSTYLE BackColor="LightSteelBlue">
 </ALTERNATINGITEMSTYLE>
 <headERSTYLE BackColor="RoyalBlue" HorizontalAlign="Center"></headERSTYLE>
 <COLUMNS>
   <asp:boundcolumn HeaderText="Name" DataField="Name"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Title" DataField="Title"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Phone" DataField="Phone"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Email" DataField="Email"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="Salary" DataField="Salary"></asp:boundcolumn>
   <asp:boundcolumn HeaderText="SS#" DataField="SSNum"></asp:boundcolumn>
 </COLUMNS>
</asp:datagrid>

完整的代码隐藏类

我包含这些代码是为了那些不想下载解决方案的人。这将使您更好地理解提供的解决方案。以下是一些需要注意的事项

Populate DataGrid 方法使用 UsersFacade 中的 GetUsers 方法。这会检索 UserDTO 的集合。在我的示例中,我不访问数据库,我只是预先填充集合并返回它。在实际应用中,这将访问数据库或 XML 文件。

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DgColWebApp
{
    /// <summary>
    /// Summary description for DgColVisibility.
    /// </summary>
    public class DgColVisibility : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.Button btnUser;
        protected System.Web.UI.WebControls.DataGrid dgExample;
        protected System.Web.UI.WebControls.Button btnAdminView;
        protected System.Web.UI.WebControls.Label lblUiView;
        private UserFacade userFacade = new UserFacade();
        private enum UserView{User, Admin};
    
        private void Page_Load(object sender, System.EventArgs e)
        {
            if(!this.IsPostBack)
            {
                this.lblUiView.Text = UserView.User.ToString();
                this.PopulateGrid();
            }
        }

        private void PopulateGrid()
        {
            UserDTO[] users = userFacade.GetUsers();
            // Are there any users?            
            if(users == null)
            {
                return;
            }

            DataTable dt = new DataTable();
            //  Add the columns to the DataTable.
            dt.Columns.Add("Name");
            dt.Columns.Add("Title");
            dt.Columns.Add("Email"); 
            dt.Columns.Add("Phone");
            dt.Columns.Add("Salary");
            dt.Columns.Add("SsNum");
            // Loop through all of the users.
            foreach(UserDTO user in users)
            {
                // Generate the row.
                DataRow dr = dt.NewRow();
                // Add the data to the row.
                dr["Name"]        = user.Name;
                dr["Title"]        = user.Title;
                dr["Email"]        = user.Email;
                dr["Phone"]        = user.Phone;
                dr["Salary"]    = user.Salary;
                dr["SsNum"]        = user.SsNum;
                // Add the row to the datatable.
                dt.Rows.Add(dr);
            }
            
            // Bind the Data to the Grid.
            this.BindDataGrid(dt);
            this.HideShowColumns(this.dgExample);
        }

        /// <summary>
        /// This method Binds a DataTable to the example DataGrid.
        /// </summary>
        /// <PARAM name="dt"></PARAM>
        private void BindDataGrid(DataTable dt)
        {
            DataView dv = dt.DefaultView;

            // Bind the Data.
            this.dgExample.DataSource = dv;
            this.dgExample.DataBind();
        }

        private void HideShowColumns(DataGrid dg)
        {
            if(dg == null)
            {
                return;
            }
            
            // Loop through all of the columns in the grid.
            foreach(DataGridColumn col in dg.Columns)
            {
                // Are we in UserView Mode?
                if(this.lblUiView.Text == UserView.User.ToString())
                {
                    // Hide the Salary and SS# Columns.
                    if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
                    {
                        col.Visible = false;
                    }
                }
                // Are we in AdminView Mode?
                else if(this.lblUiView.Text == UserView.Admin.ToString())
                {
                    // Show the Salary and SS# Columns.
                    if(col.HeaderText == "Salary" || col.HeaderText == "SS#")
                    {
                        col.Visible = true;
                    }
                }
            }
        }
        
        private void btnUser_Click(object sender, System.EventArgs e)
        {
            this.lblUiView.Text = UserView.User.ToString();
            this.PopulateGrid();
        }

        private void btnAdminView_Click(object sender, System.EventArgs e)
        {
            this.lblUiView.Text = UserView.Admin.ToString();
            this.PopulateGrid();
        }
    }
}

屏幕截图

下面是具有备用视图的网格示例。一个视图是用户视图,其中隐藏了一些列。另一个视图是管理员视图,其中显示所有列。

用户视图(列已隐藏)

User View

管理员视图(所有列都可见)

Admin View

结论

通过索引引用列的问题可能会变成一场噩梦。正如你所看到的,这个问题有一个简单的解决方案。

注意:如果你的 AutoGenerateColumns = true;,此示例将不起作用。

© . All rights reserved.