show/hide grid-view column by column name

你离开我真会死。 提交于 2019-12-11 05:48:22

问题


I'm creating a web project in Visual Studio 2012 using C# which fetch data from database and shows in a grid-view. There are many number of columns in the database, which shows on the grid-view as it is. I want to make an option for the user to eliminate unwanted columns using check-boxes and after checking, on a button click it must update.

I found how to hide a column by its column name. I need to find out how can I display it with the column name.

if (CheckBox3.Checked)
{
    dt.Columns.Remove("Site_name");
    GridView1.DataSource = dt;
    GridView1.DataBind();
}
else
{
    dt.Columns.Show("Site_name"); //I want a code to display, using column name.
}

回答1:


Well I found a very simple way show and hide a particular column using check-box on a button click.

 if (CheckBox3.Checked == false)
 {
    dt.Columns.Remove("Site_name");
    GridView1.DataSource = dt;
    GridView1.DataBind();
 }



回答2:


I would not remove the whole column from the DataTable, then you can't get it back if the user wants to show it (without relaoding all from database or whatever). I would show/hide that column only.

You have to find the index of the column first. DataControlFieldCollection.IndexOf only supports to find an index by a DataControlField not by it's HeaderText. If you often need to find the index of a GridView-column by it's name you can use this extension method:

public static class Extensions
{
    public static int GetColumnIndex(this DataControlFieldCollection columns, string columnName, StringComparison comparison = StringComparison.CurrentCultureIgnoreCase)
    {
        for(int index = 0; index <  columns.Count; index++)
            if(columns[index].HeaderText.Equals(columnName, comparison))
                return index;
        return -1;
    }
}

Now you can use this code:

int colIndex = GridView1.Columns.IndexOf("Site_name");
GridView1.Columns[colIndex].Visible = isColumnVisible; // acc. to your logic


来源:https://stackoverflow.com/questions/25639693/show-hide-grid-view-column-by-column-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!