How to Get datakey, rowindex or row from a gridview row event

Source: Internet
Author: User
When using a gridview, it's very common to raise an event from a control inside the gridview and then handle it in the code behind file. in most cases, we need know which row that control is in and what is the row index or the values of datakey in that row. in this article, we will look through several ways to do so. they may not be comprehensive or the best solution but shocould be able to deal with most situations.

The first two methods shows how to handle the button like control (implement ibuttoncontrol) and deals with the events have a "click" nature. the last one shows how to handle any event raised by any control to retrieve the information you need.


1. Using the embedded "select" command

This shoshould be the most easy and convenient way to get the selected row.

To do so, you can tick the check box for a gridview in the design view:



This will result the following codes in the. aspx file:
ASP: commandfield showselectbutton = "true"/>

Another way is using a button in a template field and assign "select" to its commandname:
ASP: templatefield>
Itemtemplate>
ASP: button id = "btnselect" runat = "server" text = "select" commandname = "select"/>
Itemtemplate>
ASP: templatefield>

And then, you need to create and handle the "selectedindexchanged" event for the gridview.

To do so, first register the event in the gridview attributes Tag:
ASP: gridview/* all other attributes */
Onselectedindexchanged = "gridview1_selectedindexchanged">

Then, handle it in the code behind file:
Protected void gridview1_selectedindexchanged (Object sender, eventargs E)
{
Gridview GV = (gridview) sender;
Displayindexanddatakey (GV. selectedindex. tostring (), GV. selecteddatakey. value. tostring ());
}

The rowindex and datakey can be retrieved from the selectedindex and selecteddatakey properties.

Using the "select" command shoshould be your first choice, but in some case you may not want to use the "select" or you 've already used it and still want to have another button click event. how to achieve that?


2. Using the "rowcommand" event in the gridview

Let's say you need a button in each row and do something when click it. You cannot use the first method because it already has other usage.

Gridview provides another event called "rowcommand" to deal with such situation.

First, we need to register the event to the gridview. You can do this in the design view:



Or just do it like we register the "select" event in Method 1:
ASP: gridview/* all other attributes */
Onrowcommand = "gridview1_rowcommand"

Second, we need create a button in a template field:
ASP: templatefield>
Itemtemplate>
ASP: button id = "btnclick" runat = "server" text = "click" commandname = "click" commandargument = '# eval ("customerid") %>'/>
Itemtemplate>
ASP: templatefield>

Please note we set the commanname to "click" and the commandargument to ''. I will explain this soon in the code behind file.

Last, we can now handle the event in the code behind file:
Protected void gridview1_rowcommand (Object sender, gridviewcommandeventargs E)
{
// Check the command name
If (E. commandname = "click ")
{
// Do some thing here.
}
}

In most case, you may need the datakey for the row where the button raised the event. the most simple way is to use the commandargument properties. as you 've already noticed, we use eval () to assign the "mermerid" to commandargument. then in the code, you can retrieve it like this:
String id = E. commandargument. tostring ();

Please note, the commandargument can be any string but usually we set datakey to it as datakey is the link between the row and your dataset. to go further, you can use your own function to instead the eval () and bind value which cannot be simply retrieved from the datasource.

But can we assign the rowindex instead of datakey? As eval () only can bind the value from the datasource, it seems there is no way to assign the rowindex to commandargument. But we do have an alternative way! We can use the rowdatabound event in the gridview and then bind the rowindex to commandargument.

First, register the event:
ASP: gridview/* all other attributes */onrowdatabound = "gridview1_rowdatabound">

Then, assign the rowindex to commandargument:
Protected void gridview1_rowdatabound (Object sender, gridviewroweventargs E)
{
If (E. Row. rowtype = datacontrolrowtype. datarow)
{
Button BTN = (button) (E. Row. findcontrol ("btnclick "));
BTN. commandargument = E. Row. rowindex. tostring ();
}
}

Finally, retrieve the rowindex through E. commandargument:
Int rowindex = int. parse (E. commandargument. tostring ());
Gridview GV = (gridview) sender;
String datakey = GV. datakeys [rowindex]. value. tostring ();

Actually, you may have noticed that the datakey can be retrieved thought the rowindex. yes, the datakeys collection will keep the right sequence when you sort, page the gridview data. thus you will be guaranteed always get the correct datakey to the row. so you may consider always pass the rowindex instead of datakey.

For those who think using the rowdatabound event can be tedious, there do have a short cut. you can use the butonfield in the gridview. the commandargument will be automatically set as the rowindex. for example:
ASP: buttonfield commandname = "click2" text = "use buttonfield" buttontype = "button"/>

When handling the rowcommand, if E. commandname = "click2", then E. commandargument will have the value of the rowindex although we don't explicitly assign it. the drawback is you will lose the flexibility of using template field.

3. Handling the event from the control itself

The above 2 methods have a flaw by nature. thus they require the control must implement ibuttoncontrol interface to use the commandname. somehow you may need to handle the control such as checkbox, dropdonwlist and etc that don't provide you a commandname property. or you just want to handle the event in the button_click rather than the gridview events.

First we shoshould know that all the controls in a ASP. NET page are all organized in a hierarchy so we can always go up to the parent control and in the end is the page. here we can either use namingcontainer or parent property to achieve our goal. they are similar but slightly different in hierarchy.

Using namingcontainer property is simpler. The hierarchy here is the gridview contains gridviewrow and the gridviewrow contains the button which raised the event. bear this in mind, we have the following code:
// Gets the button that raised the event
Button BTN = (button) sender;

// Get the row which the button is in.
Gridviewrow ROW = (gridviewrow) BTN. namingcontainer;
// Get the gridview contains that row.
Gridview GV = (gridview) Row. namingcontainer;
Int rowindex = row. rowindex;
String datakey = GV. datakeys [rowindex]. value. tostring ();

So we can easily get the rowindx and datakey.

Using Parent property is cumbersome as the hierarchy is more complex and contains one type (childtable) which is only use by. net Framework. the hierarchy is gridview-> childtalbe-> gridviewrow-> datacontrolfieldcell-> button:
// Gets the button that raised the event
Button BTN = (button) sender;
// Gets the cell
Datacontrolfieldcell cell = (datacontrolfieldcell) BTN. parent;
// Gets the row
Gridviewrow ROW = (gridviewrow) cell. parent;
// Gets the gridview
// Please note the row. parent will return a childtable which is a type supports the. NET Framework infrastructure.
// It's not used by the user so we don't have a type for that.
Gridview GV = (gridview) (row. Parent). Parent );

There is no need to use the Parent property as the namingcontainer property can do the job better. But to know something more is not a bad idea.

By using this third method, you can get the rowindex and datakey from any event raised by a control. e. g. you can handle a checkbox "checkchange" event (remember you need to set autopostback = "true" in the checkbox properties ). A sample codes:
Itemtemplate>
ASP: checkbox runat = "server" autopostback = "true"
Oncheckedchanged = "cbtest_checkedchanged"/>
Itemtemplate> protected void cbtest_checkedchanged (Object sender, eventargs E)
{
// Gets the control that raised the event
Checkbox cb = (checkbox) sender;

// Get the row which the control is in.
Gridviewrow ROW = (gridviewrow) CB. namingcontainer;
// Get the gridview contains that row.
Gridview GV = (gridview) Row. namingcontainer;

Int rowindex = row. rowindex;
String datakey = GV. datakeys [rowindex]. value. tostring ();

Displayindexanddatakey (rowindex. tostring (), datakey );
}
Conclusion

I have showed three different ways to get the rowindex AND THE datakey from a control event inside a gridview. They all have different strength so you need to choose them wisely.

 


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.