Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Hide the Datagrid Columns Which are Not Intended to be Displayed at Runtime

0.00/5 (No votes)
8 Apr 2010 1  
Hide the datagrid columns which are not intended to be displayed at runtime

Introduction

This article describes how to hide a particular column (e.g., ProductID or CategoryID) in DataGrid (in Windows Form) which is not intended to be displayed to the end user. In this article specifically, I am going to describe how to hide the columns in DataGrid while using related data.

Background

While working on my project, I need to display related data in DataGrid. But I don't want to display the ID columns in both the parent and child columns, and for that I had to do some research and at the end, I found the solution. I am posting here to help others who may also need to do the same as me.

Using the Code

In the sample code submitted here, I have used Northwind database. From that, I have used Categories and Products table to explain the relational data representation by hiding unwanted columns.

First of all, use the following code block to load the data from database.

private void LoadData()
{ 
    DataTable dtCategories = new DataTable("Categories");
    DataTable dtProducts = new DataTable("Products");
    ds = new DataSet();
    using (SqlConnection connection = new SqlConnection
	("Server=localhost;Initial Catalog=Northwind;Integrated Security=True"))
    {
        using (SqlCommand command = new SqlCommand
	("Select CategoryID,CategoryName,Description from Categories", connection))
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {
                adapter.Fill(dtCategories);
                ds.Tables.Add(dtCategories);
            }
        } 
        using (SqlCommand command = new SqlCommand
	("select ProductID,CategoryID,ProductName,UnitPrice,
	UnitsInStock,UnitsOnOrder from Products;", connection))
        {
            using (SqlDataAdapter adapter = new SqlDataAdapter(command))
            {  
                adapter.Fill(dtProducts);
                ds.Tables.Add(dtProducts); 
            } 
        }
    }
    //Now add the relations to the dataset.
    DataRelation dataRelationCategoryProduct = 
	new DataRelation("CategoryProduct",dtCategories.Columns["CategoryID"], 
	dtProducts.Columns["CategoryID"]);
        ds.Relations.Add(dataRelationCategoryProduct);
    dataGrid1.DataSource = ds;
    dataGrid1.DataMember = "Categories";
}  

Here I have made a relation of Categories and Products table at runtime and added it to the dataset's Relations collection.

After Loading data, use the following line to register the TableStyles.CollectionChanged event for the particular datagrid.

dataGrid1.TableStyles.CollectionChanged += 
	new CollectionChangeEventHandler(TableStyles_CollectionChanged);

After doing this, add the table styles to the datagrid which removes the unwanted columns from datagrid. Use the following code for that:

private void AddTableStyles()
{
    if (!dataGrid1.TableStyles.Contains(tsCategory))
    {
        tsCategory = new DataGridTableStyle();
        tsCategory.MappingName = "Categories";
        dataGrid1.TableStyles.Add(tsCategory);
    }
    if (!dataGrid1.TableStyles.Contains(tsProduct))
    {
        tsProduct = new DataGridTableStyle();
        tsProduct.MappingName = "Products";
        dataGrid1.TableStyles.Add(tsProduct);
    }
} 

Here I have added two DataGridTableStyles objects for each table.

Now implement the main logic which hides the unwanted columns in the datagrid.

private void TableStyles_CollectionChanged(object sender, CollectionChangeEventArgs e)
{
    if (dataGrid1.TableStyles.Contains(tsCategory))
   {
        if(dataGrid1.TableStyles["Categories"].GridColumnStyles
            .Contains(dataGrid1.TableStyles["Categories"].GridColumnStyles["CategoryID"]))
        {                 
            dataGrid1.TableStyles["Categories"].GridColumnStyles
            .Remove(dataGrid1.TableStyles["Categories"].GridColumnStyles["CategoryID"]);
        }                
    }
    if (dataGrid1.TableStyles.Contains(tsProduct))
    {
        if(dataGrid1.TableStyles["Products"].GridColumnStyles
            .Contains(dataGrid1.TableStyles["Products"].GridColumnStyles["ProductID"]))
        {
            dataGrid1.TableStyles["Products"].GridColumnStyles
            .Remove(dataGrid1.TableStyles["Products"].GridColumnStyles["ProductID"]);
        }
        if(dataGrid1.TableStyles["Products"].GridColumnStyles
            .Contains(dataGrid1.TableStyles["Products"].GridColumnStyles["CategoryID"]))
        {
            dataGrid1.TableStyles["Products"].GridColumnStyles
            .Remove(dataGrid1.TableStyles["Products"].GridColumnStyles["CategoryID"]);
        }
    }
} 

For the above code block, first I have checked whether DataGrid's TableStyles collection contains the particular TableStyle or not. If we don't check this, then it will throw an exception. The first if block of the above code applies the TableStyle for the "Categories" table to hide the "CategoryID" column in the datagrid and the second if block hides the "ProductID" and "CategoryID" from "Products" table.

One more thing to do is you have to register DataGrid's Navigate event. Do this using Properties window or use the following line to register the event.

dataGrid1.Navigate += new NavigateEventHandler(dataGrid1_Navigate);

Write the above line in Form's Load method.

And finally write the following lines of code which respond to the datagrid's registered Navigate event.

private void dataGrid1_Navigate(object sender, NavigateEventArgs ne)
{
    /*On each navigation, call the TableStyles_CollectionChanged 
    method to apply our settings.*/
    TableStyles_CollectionChanged(null, null);            
} 

That's all!!!

Now you can test....

It will hide the "CategoryID" column when datagrid is displaying the "Categories" table data and will hide the "ProductID" and "CategoryID" columns when displaying the "Products" table data.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here