Click here to Skip to main content
Click here to Skip to main content

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

, 8 Apr 2010
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jatin.Prajapati.ER
Web Developer
India India
Currently working in Software development company in Baroda. Completed B.E (Information Technology) from G.H. Patel College of Engineering and Technology, Vallabh Vidhyanagar. Interested in programming C#.

Comments and Discussions

 
QuestionInteresting !!! but why ? PinmemberNavnath R. Kale9-Apr-10 11:04 
AnswerRe: Interesting !!! but why ? PinmemberNavnath R. Kale9-Apr-10 22:09 
GeneralNice article PinmemberGaurav Dudeja India8-Apr-10 20:15 
GeneralInteresting PinmemberStockportJambo3-Nov-07 22:03 
GeneralDesigner PinmvpMark Nischalke3-Nov-07 3:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140721.1 | Last Updated 9 Apr 2010
Article Copyright 2007 by Jatin.Prajapati.ER
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid