user3985746
user3985746

Reputation:

show/hide grid-view column by column name

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.
}

Upvotes: 1

Views: 3874

Answers (2)

user3985746
user3985746

Reputation:

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();
 }

Upvotes: 1

Tim Schmelter
Tim Schmelter

Reputation: 460158

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

Upvotes: 0

Related Questions