IntroductionIn this article we will see how we can Show Hide the columns in a DataGrid.
Creating WPF Application
ProjectFire up Visual Studio 2008 and Create a WPF Application
and name the project as HideUnhideDGInWPF.
Here
is the thing; we will have a DataGrid which will columns Auto Generated. We will
have a Wrap Panel that will have the Check Boxes.
So here we go, add a
class to generate sample data.
#region Employee Class
public class Employee
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EmailID { get; set; }
public string Contact { get; set; }
}
#endregion And
create sample data and bind it to the DataGrid.
List employeeList = new List();
public Window1()
{
InitializeComponent();
for (int i = 1; i <= 20; i++)
{
Employee emp = new Employee
{
ID = i,
FirstName = "FirstName" + i.ToString(),
LastName = "LastName" + i.ToString(),
EmailID = "FirstName " + i.ToString() + ".LastName" + i.ToString() + "@some.com",
Contact = "9999999" + i.ToString()
};
employeeList.Add(emp);
}
dgData.AutoGeneratedColumns+=new EventHandler(dgData_AutoGeneratedColumns);
dgData.ItemsSource = employeeList;
}
Now
in the AutoGeneratedColumns event handler add the following code to generate the
CheckBoxes.
private void dgData_AutoGeneratedColumns(object sender, EventArgs e)
{
foreach (DataGridColumn item in dgData.Columns)
{
chk = new CheckBox();
checkBoxList.Add(chk);
wrapColumns.Children.Add(chk);
chk.Width = 100;
chk.Height = 22;
chk.Content = item.Header;
chk.IsChecked = true;
chk.Checked += new RoutedEventHandler(chk_Checked);
chk.Unchecked += new RoutedEventHandler(chk_Unchecked);
}
} Now
we will work on the Hiding part for the Columns.
#region Hide Column
void chk_Unchecked(object sender, RoutedEventArgs e)
{
List chkUnchekList = new List();
chkUnchekList.Clear();
foreach (CheckBox item in checkBoxList)
{
if (item.IsChecked == false)
{
chkUnchekList.Add(item.Content.ToString());
}
}
foreach (DataGridColumn item in dgData.Columns)
{
if (chkUnchekList.Contains(item.Header.ToString()))
{
dgData.Columns.Remove(item);
break;
}
}
}
#endregion The
following code is for un hiding the columns when uncheked.
#region Un-Hide
void chk_Checked(object sender, RoutedEventArgs e)
{
dgData.AutoGeneratedColumns -= new EventHandler(dgData_AutoGeneratedColumns);
List chkCheckList = new List();
chkCheckList.Clear();
foreach (CheckBox item in checkBoxList)
{
if (item.IsChecked == false)
{
chkCheckList.Add(item.Content.ToString());
}
}
dgData.ItemsSource = null;
dgData.ItemsSource = employeeList;
foreach (string item in chkCheckList)
{
foreach (DataGridColumn column in dgData.Columns)
{
if (column.Header.ToString() == item)
{
dgData.Columns.Remove(column);
break;
}
}
}
}
#endregion That's
it, we have actually done it. Run the application.
And
when Checked or Unchecked, it will work.

you can also download the sample code used in the above example.
Hope
this article helps.