Click here to Skip to main content
15,892,161 members
Articles / Web Development / ASP.NET
Article

ASP.NET - C# Retrieve DataGrid Cell via HeaderText

Rate me:
Please Sign up or sign in to vote.
4.20/5 (8 votes)
15 Aug 20052 min read 107K   975   36   6
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:

C#
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:

C#
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:

C#
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.

C#
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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey9-Feb-12 21:10
professionalManoj Kumar Choubey9-Feb-12 21:10 
GeneralSQL in C# Pin
Diamond118-Jun-06 21:47
Diamond118-Jun-06 21:47 
Generalgood! Pin
FutureSoft10-Jan-06 16:30
FutureSoft10-Jan-06 16:30 
up

I DON'T KNOW
GeneralAuto-Generated columns Pin
Member 142630224-Aug-05 7:20
Member 142630224-Aug-05 7:20 
GeneralRe: Auto-Generated columns Pin
Kenneth Young24-Aug-05 7:25
Kenneth Young24-Aug-05 7:25 
Questionhai selected row alone get processed Pin
sangeethait2831-May-07 8:05
sangeethait2831-May-07 8:05 

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

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