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

Accessing individual cell data in a GridView through the CommandArgument value

Rate me:
Please Sign up or sign in to vote.
4.00/5 (1 vote)
12 Sep 2007CPOL3 min read 74K   235   22   11
Setting the CommandArgument value of a GridView cell at RowDataBound.

Introduction

I ran into a problem the other day where I needed to catch the value of a clicked cell in a GridView. By default, the RowCommand contains the RowIndex in the CommandArgument, but there is no way of knowing which column fired the event. The solution was found in setting the CommandArgument value of the cell at run-time when you bind the rows of the GridView. This article will show you how to do this in a very quick and simple way.

Background

Thanks to forum.asp.net, I was pointed into the right direction by setting the CommandArgument of the cell during the RowDataBound event. Question was, of course… how? Until by accident I ended up with the solution I will present now.

The Application

I will use a very small application to show how to do this. The application shows the data of music groups from an XML file with the help of the XmlDataSource object. I would never use those DataSource objects in real applications, but they are great to put something together in just a few minutes for prototyping purposes. The data exist for the band name and four members. When clicking on a member, the name is displayed in a label above the GridView.

Screenshot - CommandArgument.jpg

I am not going into how to bind the XML file to the GridView. There are many articles on something called the Internet that handle this topic. I will just show you the RowDataBound and RowCommand event handlers of this GridView. (I also found out how hard it is to find four-member groups when you actually need them.)

To run the example, download the source, open the project file, and run it through Visual Studio 2005.

RowDataBound

The RowDataBound event is triggered every time a row of the GridView is bound to data. It is a great place to make some last changes to the data before it is displayed to the user.

C#
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[1].Controls[0]).CommandArgument =
            ((LinkButton)e.Row.Cells[1].Controls[0]).Text;
        ((LinkButton)e.Row.Cells[2].Controls[0]).CommandArgument =
            ((LinkButton)e.Row.Cells[2].Controls[0]).Text;
        ((LinkButton)e.Row.Cells[3].Controls[0]).CommandArgument =
            ((LinkButton)e.Row.Cells[3].Controls[0]).Text;
        ((LinkButton)e.Row.Cells[4].Controls[0]).CommandArgument =
            ((LinkButton)e.Row.Cells[4].Controls[0]).Text;
    }
}

The above code checks first if the row is of type 'DataRow'. Next, we navigate to the different cells of the row and cast the first control to a LinkButton. This cast is very important and depends on what type of button you use in your GridView. If you set the type to 'button', then you need to cast the control to a Button. In my case, I use the 'link' type so I have to cast it to a LinkButton control. Once you cast it to the correct control, you can set the CommandArgument property to the Text value without any problems, as shown above.

RowCommand

Once you set the CommandArgument, the only thing left to do is retrieve it when clicking on the link. Clicking on the link fires a normal RowCommand event, but now, you find that the CommandArgument is not the row index, but the text of the clicked cell. Of course, you need to set the CommandName of all ButtonFields to the same name. Next, you just do the same as you always do with the RowCommand, as shown below:

C#
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "ShowMember")
    {
        lblResult.Text = "You clicked Member '" + e.CommandArgument.ToString() + "'";
    }
}

Conclusion

As you can see, a very simple solution, that unfortunately took me almost a whole day to figure out. This, of course, included waiting for response out from America. Why do those guys always sleep when we are awake?? My biggest problem was to access the control and the CommandArgument property when binding the row. I was actually trying to convert it to a ButtonField, until (I still don't know why) I suddenly mistyped and converted it to a LinkButton. Of course, now it all makes perfect sense to me. Depending on what type of button you select in the GridView, that is the kind of control generated at run-time and needs to be used when referring to it. This discovery helped me a lot in my current project, and I hope it will help others as well who fall on this article. This is my first article to The Code Project. For years, this has become one of my main resources, so I thought it is time to give something back (or at least try to).

License

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


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

Comments and Discussions

 
QuestionHow to make 'ButtonField' at the run time? Pin
ankitCsharpAsp1-Feb-09 20:13
ankitCsharpAsp1-Feb-09 20:13 
Hi guys, I am building a visual seat booking system. So I need all cells, rows, columns be auto generated(run time). So I need littlefool's buttonfield be created at runtime.
I created button at runtime and also retrived it's value but can't retrive the selected row no. Please help me I am giving my practice code for the 1st column.

void addBookingTable()
{

.........................
gvbooking.DataSource = dv;
gvbooking.DataBind();
}
Button newBtn;
protected void gvbooking_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
newBtn = new Button();
newBtn.Text = e.Row.Cells[1].Text;
newBtn.Click += new EventHandler(newBtn_Click);
e.Row.Cells[1].Controls.Add(newBtn);
newBtn.Height = e.Row.Cells[3].Height;
newBtn.BorderStyle=0;
}
}
protected void newBtn_Click(object sender, EventArgs e)
{

TextBox1.Text = newBtn.Text;

}

***) Please help me any one of the one process so that I can retrieve both cell value as well as selected row no. of the gridview.
GeneralRow Index Pin
Joey Esquibel25-Jun-08 12:01
Joey Esquibel25-Jun-08 12:01 
GeneralRe: Row Index Pin
danny_pow19-Dec-08 3:10
danny_pow19-Dec-08 3:10 
GeneralThanks Pin
merlin98113-Sep-07 6:25
professionalmerlin98113-Sep-07 6:25 
GeneralOr.. Pin
ColinMacKenzie12-Sep-07 6:42
ColinMacKenzie12-Sep-07 6:42 
GeneralRe: Or.. Pin
Littlefool12-Sep-07 7:10
Littlefool12-Sep-07 7:10 
GeneralRe: Or.. Pin
ColinMacKenzie12-Sep-07 12:07
ColinMacKenzie12-Sep-07 12:07 
GeneralRe: Or.. Pin
Littlefool13-Sep-07 0:07
Littlefool13-Sep-07 0:07 
GeneralRe: Or.. Pin
ColinMacKenzie13-Sep-07 1:02
ColinMacKenzie13-Sep-07 1:02 
GeneralRe: Or.. Pin
Littlefool13-Sep-07 1:13
Littlefool13-Sep-07 1:13 
GeneralRe: Or.. Pin
sedat9528-May-09 2:17
sedat9528-May-09 2:17 

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.