SIGN UP MEMBER LOGIN:    
ARTICLE

DataGrid Customization Part-II: Custom Sorting and DataGrid Column Hiding

Posted by Mahesh Chand Articles | Windows Forms C# August 13, 2002
How to I get the name and index of the Column headers? How do I find out if mouse click right click was on a column
Reader Level:
Download Files:
 

In DataGrid Customization Part 1, I covered the following topics:

  • How to I get the name and index of the Column headers?
  • How do I find out if mouse click right click was on a column header?
  • How do I get the row and column numbers of current selected cell?
  • How to change the positions of columns?

Here I will add more functionality to the same application.

In this article, I am going to cover two key topics. First, how to implement custom sorting and second how to hide or remove a DataGrid columns by removing on the column header.

When you will run the application and right mouse click on the DataGrid column header, you will see a pop up menu with three items - Sort Ascending, Sort Descending, and Remove Column and so on.

Adding a context menu to a Windows application is pretty simple. Just drag a ContextMenu from Toolbox to the form and add three items as shown in Figure 1.

Now you can write the click event handlers for these menus by simply double clicking on the menu items. This is where we will write our code to sort and hide DataGrid columns.

First of all, we need to add some variables to the application. The best bet for you is to download the source code and browse its contents. The variables are listed as following:

// Developer defined variables
private OleDbConnection conn = null;
private string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";
private string sql = null;
private DataSet ds = null;
private string colHeadName = null;
private DataGridColumnStyle dcStyle = null;
private DataView dtView = null;
private System.Windows.Forms.ContextMenu columnHeadMenu;
private OleDbDataAdapter adapter = null;

The FillDataGrid method fills data to the DataGrid from Northwind database. This method is listed in the following listing. As you can see from this code, I also create a DataView object called dtView, which will be used in sorting.

Note: Actually you can also read sorted data by using a SELECT.. FROM ...ORDER BY SQL statement but you need to load data from database every time you want to sort the data, which makes application slower but is advisable in a multi-user and real-time data processing environments. In simple client server or desktop applications, when there is no other user modifying data, this approach is advisable.

private void FillDataGrid()
{
sql = "SELECT * FROM Customers";
conn =
new OleDbConnection(connectionString);
adapter =
new OleDbDataAdapter(sql, conn);
ds =
new DataSet("Customers");
adapter.Fill(ds, "Customers");
dtView = ds.Tables[0].DefaultView;
dataGrid1.DataSource = dtView;
// By default there is no DataGridTableStyle object.
// Add all DataSet table's style to the DataGrid
foreach(DataTable dTable in ds.Tables)
{
DataGridTableStyle dgStyle =
new DataGridTableStyle();
dgStyle.MappingName = dTable.TableName;
dataGrid1.TableStyles.Add(dgStyle);
}
// DataGrid settings
dataGrid1.CaptionText = "DataGrid Customization";
dataGrid1.HeaderFont =
new Font("Verdana", 12);
}

Now next step is to load the context menu when a user right clicks on the DataGrid column header. To do so, you can write the code on the DataGrid's mouse down event. The following code does the trick for you. As you can see from this code, I set dataGrid1.ContextMenu = columnHeadMenu, where columnHeadMenu is the name of the context menu you added in the previous step. After adding the context menu, A get the DataGridColumnStyle of the current column, which will be used when you want to hide the column.

string
str = null;
Point pt =
new Point(e.X, e.Y);
DataGrid.HitTestInfo hti = dataGrid1.HitTest(pt);
// If right mouse button clicked
if(e.Button == MouseButtons.Right)
{
if(hti.Type == DataGrid.HitTestType.ColumnHeader)
{
dataGrid1.ContextMenu = columnHeadMenu;
DataGridTableStyle gridStyle = dataGrid1.TableStyles["Customers"];
colHeadName = gridStyle.GridColumnStyles[hti.Column].MappingName.ToString();
dcStyle = gridStyle.GridColumnStyles[hti.Column];
}
}

The following code sorts data based on the menu item click. As you can see from the code, sorting is pretty simple. I just set the Sort property of DataView and calls DataGrid's Refresh method.

private void SortAscMenu_Click(object sender, System.EventArgs e)
{
if(! colHeadName.Equals(string.Empty))
{
dtView.Sort = colHeadName + " ASC";
dataGrid1.Refresh();
}
}
private void SortDescMenu_Click(object sender, System.EventArgs e)
{
if(! colHeadName.Equals(string.Empty))
{
dtView.Sort = colHeadName + " DESC";
dataGrid1.Refresh();
}
}

Now last step left is Column hiding. The simplest way to hide or remove a column of a DataGrid by setting a column's width to 0. The following code is written on the Remove Column menu item event handler.

private void RemoveColMenu_Click(object sender, System.EventArgs e)
{
dcStyle.Width = 0;
}

Just download the source code, right click on the DataGrid's Column header and select any menu item and see the code in action.

I will be back with more tips and tricks.

Cheers!

Login to add your contents and source code to this article
share this article :
post comment
 

Hi i would like to know, how can I expand a child table in a parent table? Im in VB.Net.  Exemple i got a name adress phone number columns and when i click on one name, it expand me the last orders from that customer all that information can be took from a child table in an Access database. How can i do that?

Posted by Charles Feb 25, 2010

Hi, iam in windows application with c#. i have textbox and datagriview i entered "productid" in textbox, it can fetch record and display in datagridview (1st row).. again i enter "productid" in textbox ,it can also fetch and display data in 2nd row ot hte datagrid... like that how many time i enter the productid ,that no:of rows created in datagridview..

Posted by murali krishna Dec 11, 2007

Unfortunately I do not send custom code to every body. Check out Windows Forms controls section of this site and look for Add, Update, and Delete in DataGrid.

If you want to add text from a TextBox to a DataGrid, there is no quick way. You will have to learn how data binding works in a DataGrid, what DataTable and DataSet objects are, and how you can add text from your TextBox to a DataTable and display that in the Grid.

Posted by Mahesh Chand Jun 26, 2007

Please send me code. How to add values from textbox to data grid. and how to edit a cell value from the data grid.

Posted by VIMALA MUTHU Jun 23, 2007

As it says in the beginning of the article, they are covered in Part 1, which is in the Windows Forms section. Here is the link:

http://www.c-sharpcorner.com/UploadFile/mahesh/DataGridCustomizationPart-I11252005054458AM/DataGridCustomizationPart-I.aspx

Posted by Mahesh Chand Mar 20, 2007
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites - Click Here!
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor