Click here to Skip to main content
15,886,737 members
Articles / Web Development / ASP.NET

Reference GridView Cells Using Column Names

Rate me:
Please Sign up or sign in to vote.
3.00/5 (4 votes)
27 Aug 2009CPOL2 min read 79.6K   10   7
Reference GridView cells using column names.

Introduction

This article will address the need to make changes to cells on an ASP.NET GridView object based on its databound columns. Searching online for solutions, I have found that many examples that attempt to reference a cell in a GridView object do so by either using a .FindControl() method to search for the particular cell or by referencing the cell with its index position in the GridView. These solutions did not satisfy me since I needed a way to reference the cells based on the column names of the datasource bound to the GridView. This way, the order of my cells could change and I could still reference them directly without having to search the whole HTML page to find them, as is done with .FindControl(). The solution I devised below uses the .Ordinal property of the DataTable’s column to return the index that would correspond to the index of a cell displayed in the GridView. This way, I can reference the index of a cell by using the column name of my datasource.

Using the Code

We begin the example by setting up a test scenario to show how the code will work. First, create a new WEB project in VS.NET 2008 (this example also works for .NET 2005 and 2003), and add a GridView object to the default page and call it myTestGridView. Then, add an event for RowCreated on the GridView object.

ASP.NET
<asp:GridView ID="myTestGridView" runat="server" 
      onrowcreated="myTestGridView_RowCreated"></asp:GridView>

Now, in your Page_Load event, add the following lines of code to set up a test DataTable to bind to our GridView object.

C#
protected void Page_Load(object sender, EventArgs e)
{
    //Create a dummy DataTable to attach to our GridView
    //to show how referencing cells works after DataBind().

    DataTable myTable = new DataTable("MyTestTable");
    DataRow myRow = null;

    myTable.Columns.Add("MyColumn1");
    myTable.Columns.Add("MyColumn2");
    myTable.Columns.Add("MyColumn3");

    myRow = myTable.NewRow();

    myRow["MyColumn1"] = "hello";
    myRow["MyColumn2"] = "and";
    myRow["MyColumn3"] = "good-bye";

    myTable.Rows.Add(myRow);

    //Now we bind the DataTable to the GridView.

    this.myTestGridView.DataSource = myTable;
    this.myTestGridView.DataBind();            
}

Finally, modify the event you created for RowCreated and add the following code. Notice that I'm getting a reference to the DataTabele stored in the DataSource and then using the .Ordinal property of the column I am referencing. .Ordinal will correspond to the index of the cell for the given column name.

C#
protected void myTestGridView_RowCreated(object sender, GridViewRowEventArgs e)
{
    DataTable gridDataTable = null;
    TableCell tblCell1;
    TableCell tblCell2;
    TableCell tblCell3;

    //Obtain the reference to the bound datasource, 
    //our dummy DataTable, on the GridView.

    gridDataTable = (DataTable)((GridView)sender).DataSource;

    //If a datasource is bound, then begin obtaining cell references 
    //by Column name of the bound datasource.

    if (gridDataTable != null)
    {
        //Get the cell references by Column name and ordinal position of that column.

        tblCell1 = e.Row.Cells[gridDataTable.Columns["MyColumn1"].Ordinal];
        tblCell2 = e.Row.Cells[gridDataTable.Columns["MyColumn2"].Ordinal];
        tblCell3 = e.Row.Cells[gridDataTable.Columns["MyColumn3"].Ordinal];

        //Make some fun changes to our cells and voila!

        tblCell1.BackColor = System.Drawing.Color.Red;
        tblCell2.ToolTip = "MyColumn2 is where we display our conjunctions.";
        tblCell3.Visible = false;
    }
}

History

No history yet, but will keep you posted!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


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

 
Generalvb version Pin
Bob Carter1-Sep-09 8:47
Bob Carter1-Sep-09 8:47 
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'//Create a dummy DataTable to attach to our GridView to show how referencing cells works after DataBind().

' DataTable myTable = new DataTable("MyTestTable");
Dim myTable As New DataTable("MyTestTable")

' DataRow myRow = null;
Dim myRow As DataRow


myTable.Columns.Add("MyColumn1")
myTable.Columns.Add("MyColumn2")
myTable.Columns.Add("MyColumn3")

myRow = myTable.NewRow()

myRow("MyColumn1") = "hello"
myRow("MyColumn2") = "and"
myRow("MyColumn3") = "good-bye"

myTable.Rows.Add(myRow)
myTestGridView.DataSource = myTable
myTestGridView.DataBind()
End Sub


Protected Sub myTestGridView_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myTestGridView.RowCreated
Dim gridDataTable As DataTable = Nothing
Dim gridview As System.Web.UI.WebControls.GridView
Dim tblCell1 As TableCell
Dim tblCell2 As TableCell
Dim tblCell3 As TableCell
'
' //Obtain the reference to the bound datasource, our dummy DataTable, on the GridView.
' gridDataTable = (DataTable)((GridView)sender).DataSource;
On Error Resume Next
gridview = CType(sender, System.Web.UI.WebControls.GridView)
If Err.Number <> 0 Then
Response.Write("
Err on addressing sender gridview> " & Err.Description)
Response.Flush()
Exit Sub
End If
gridDataTable = gridview.DataSource
If Not gridDataTable Is Nothing Then
tblCell1 = e.Row.Cells(gridDataTable.Columns("MyColumn1").Ordinal)
tblCell2 = e.Row.Cells(gridDataTable.Columns("MyColumn2").Ordinal)
tblCell3 = e.Row.Cells(gridDataTable.Columns("MyColumn3").Ordinal)
tblCell1.BackColor = System.Drawing.Color.Pink
tblCell2.ToolTip = "MyColumn2 is where we display our conjunctions."
tblCell2.BackColor = System.Drawing.Color.Fuchsia
tblCell3.Visible = True ';//false;
tblCell3.BackColor = System.Drawing.Color.DarkCyan
End If
End Sub
End Class
GeneralMy vote of 2 Pin
Anurag Gandhi31-Aug-09 19:14
professionalAnurag Gandhi31-Aug-09 19:14 
GeneralRe: My vote of 2 Pin
rf_libra2-Sep-14 20:48
rf_libra2-Sep-14 20:48 
QuestionWhat if the DataSource is not a DataTable Pin
Anurag Gandhi31-Aug-09 19:12
professionalAnurag Gandhi31-Aug-09 19:12 
AnswerRe: What if the DataSource is not a DataTable Pin
IanTretyakov3-Sep-09 5:54
IanTretyakov3-Sep-09 5:54 
GeneralRe: What if the DataSource is not a DataTable Pin
Anurag Gandhi3-Sep-09 9:45
professionalAnurag Gandhi3-Sep-09 9:45 
GeneralThx Pin
jamartinezac31-Aug-09 9:18
jamartinezac31-Aug-09 9:18 

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.