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

ASP.NET - C# Retrieve DataGrid Cell via HeaderText

, 15 Aug 2005
Rate this:
Please Sign up or sign in to vote.
Shows a developer how to retrieve a column or cell via the column HeaderText.

Introduction

In the previous article, Hide DataGrid Columns via HeaderText, I described how to hide a DataGridColumn via the HeaderText. If you have not read the previous article, it provides a method to hide/show columns based on a user's view. This solved the problem of referencing the index of the column which can lead to problems when you move columns around. This article is built upon that example and demonstrates how to retrieve data in the DataGrid by the column's HeaderText. You will now have the ability to use the text of the header for both populating and retrieving data from the DataGrid.

I ran into the problem of referencing the index of a column a while back. As you know, users frequently want to add, remove, and move columns in a grid. This can become a tedious task if you have many columns in the grid. There is a simple solution to the indexing nightmare. For the simplicity of the example, I opted to include the methods that retrieve a cell or column by HeaderText in the page's class. In your application, you could choose to create a custom DataGrid and implement the methods in it, or create a helper class that each grid will call, or just do what I did.

The code

Below is an example of the method that retrieves a TableCell by the headerText. The input parameters are DataGridItem item and string headerText. To use this method, you would loop through the DataGridItems, which I will show you how to do:

public TableCell GetCellByHeaderText(DataGridItem item, 
                                       string headerText)
{
    if(item == null || headerText == null)
    {
        return null;
    }

    DataGrid dg = item.NamingContainer as DataGrid;
    int colNum = this.GetIndexByHeaderText(dg.Columns, 
                                           headerText);

    if(colNum >= 0)
    {
        return item.Cells[colNum];
    }
    // No cell found by header text.
    return null;
}

This method retrieves a DataGridColumn by the headerText. The input parameters are DataGrid dg and string headerText:

public DataGridColumn GetColumnByHeaderText(DataGrid dg, 
                                        string headerText)
{
    if(dg == null || dg.Columns == null || 
                                  headerText == null)
    {
        return null;
    }
    // Loop through each column in the grid.
    foreach(DataGridColumn col in dg.Columns)
    {
        if(col.HeaderText == headerText)
        {
            return col;
        }
    }
    // No column found by header text.
    return null;
}

This method retrieves the index of the column where the column's HeaderText matches the passed in headerText. The input parameters are DataGridColumnCollection cols and string headerText:

private int GetIndexByHeaderText(DataGridColumnCollection cols, 
                                                string headerText)
{
    if(cols == null)
    {
        return -1;
    }
    // Loop through each column in the grid.
    for(int i=0; i < cols.Count; i++)
    {
        if(cols[i].HeaderText == headerText)
        {
            return i;
        }
    }
    // No column found by header text.
    return -1;
}

Page code-behind

This method utilizes the methods shown above to retrieve the data via the HeaderText. It is placed in the page's code-behind class. The method loops through each DataGridItem in the DataGrid. This example outputs the data back on the page for demonstration purposes. In a real application, you would store the data in a database.

private void DisplayDataFromGrid()
{
    
    // Loop through the items in the grid.
    foreach(DataGridItem item in this.dgExample2.Items)
    {
        string name = this.GetCellByHeaderText(item, 
                                          "Name").Text;
        string title = this.GetCellByHeaderText(item, 
                                         "Title").Text;
        string phone = this.GetCellByHeaderText(item, 
                                         "Phone").Text;
        string email = this.GetCellByHeaderText(item, 
                                         "Email").Text;
        string salary = this.GetCellByHeaderText(item, 
                                         "Salary").Text;
        string ssnum = this.GetCellByHeaderText(item, 
                                         "SS#").Text;
        
        // Write to screen - for testing only...
        Response.Write(name);
        Response.Write(" | " + title);
        Response.Write(" | " + phone);
        Response.Write(" | " + email);
        Response.Write(" | " + salary);
        Response.Write(" | " + ssnum);
        Response.Write("<br>");
    }
}

Conclusion

By using this article's and my previous article's examples, you no longer need to reference a column by the index. You can use the HeaderText for both display and retrieval purposes. This can save you a great amount of time if your DataGrid is constantly modified.

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

Share

About the Author

Kenny Young

United States United States
Ken currently works as the Director of Software Engineering at the Pediatrics Epidemiology Center at the University of South Florida. He is involved in the architecture and design on numerous clinical trial projects. Some of the project include:
 
1. Rare Diseases Clinical Research Network
2. TrialNet - Diabetes
3. Teddy - Diabetes
4. CCOP - Cancer
5. AIDA - Diabetes

Comments and Discussions

 
GeneralMy vote of 5 Pinmembermanoj kumar choubey9-Feb-12 22:10 
GeneralSQL in C# PinmemberDiamond118-Jun-06 22:47 
Generalgood! PinmemberFutureSoft10-Jan-06 17:30 
GeneralAuto-Generated columns PinmemberJim Riner24-Aug-05 8:20 
GeneralRe: Auto-Generated columns PinmemberKenny Young24-Aug-05 8:25 
Questionhai selected row alone get processed Pinmembersangeethait2831-May-07 9:05 

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 | Terms of Use | Mobile
Web01 | 2.8.1411023.1 | Last Updated 15 Aug 2005
Article Copyright 2005 by Kenny Young
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid