In this article I will show you how you can make columns of Datagrid invisible and visible based on user interaction. I will create the columns dynamically so if you are not familiar with this approach I suggest that you check out my article Creating bound and template columns dynamically in a datagrid.

 

Introduction:

In this article I will show you how you can make columns of Datagrid invisible and visible based on user interaction. I will create the columns dynamically so if you are not familiar with this approach I suggest that you check out my article Creating bound and template columns dynamically in a datagrid.  

User Interface:

The User Interface is pretty simple which contains link buttons inside a Datagrid controls and an independent Button control.

When we click on the Hide link inside the column header that particular column will disappear. And when we click on the "View all Columns" button all the columns of the Datagrid will appear.

ItemCommand Event:

Since the link buttons are inside the Datagrid we must somehow catch the events generated by those buttons. The best place to catch all of these events is inside the ItemCommand event. You should set the "CommandName" property of link button control to some text that will distinguish the different events generated by different controls inside Datagrid.

LinkButton lb = new LinkButton();

lc.Text = "<B>" + columnName + "</B>";

lb.Text = "Hide";

lb.CommandName = "HideColumn";

Now let's see that how we can capture these events and take appropriate action when these events are generated.

privatevoid myDataGrid_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)

{

if(e.CommandName == "HideColumn")

{

LinkButton l = new LinkButton();

l = (LinkButton) e.CommandSource;

int itemIndex = l.Parent.Parent.Controls.IndexOf(l.Parent);

// Send the column id to make that column invisible

MakeColumnInvisible(itemIndex);

}}

Inside the "ItemCommand" event of the Datagrid we are checking that if the event is generated by the link button. If it is than we find the column index where the link button is clicked and we send the column index to our custom made method "MakeColumnInvisible(itemIndex)".

Let's see the MakeColumnInvisible method.

// Method to make the column invisible

privatevoid MakeColumnInvisible(int columnIndex)

{

myDataGrid.Columns[columnIndex].Visible = false;

}

Inside the MakeColumnInvisible method we simply use the columnIndex and make the particular column invisible.

That's it.

You must be wondering how I make the columns visible again. This is even more simpler, I just call the BuildDataGrid method and that's it.

// Event raised to view all the columns

privatevoid Button1_Click(object sender, System.EventArgs e)

{

BuildDataGrid();

}

I hope you like the article, happy coding.