How to get DataKey, RowIndex or Row from a GridView row event


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 should 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 should 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 should 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 '<%# Eval("CustomerID") %>'. 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 "CustomerID" 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 should 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 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 the .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 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.


 

 


内容概要:本文档主要展示了C语言中关于字符串处理、指针操作以及动态内存分配的相关代码示例。首先介绍了如何实现键值对(“key=value”)字符串的解析,包括去除多余空格和根据键获取对应值的功能,并提供了相应的测试用例。接着演示了从给定字符串中分离出奇偶位置字符的方法,并将结果分别存储到两个不同的缓冲区中。此外,还探讨了常量(const)修饰符在变量和指针中的应用规则,解释了不同类型指针的区别及其使用场景。最后,详细讲解了如何动态分配二维字符数组,并实现了对这类数组的排序与释放操作。 适合人群:具有C语言基础的程序员或计算机科学相关专业的学生,尤其是那些希望深入理解字符串处理、指针操作以及动态内存管理机制的学习者。 使用场景及目标:①掌握如何高效地解析键值对字符串并去除其中的空白字符;②学会编写能够正确处理奇偶索引字符的函数;③理解const修饰符的作用范围及其对程序逻辑的影响;④熟悉动态分配二维字符数组的技术,并能对其进行有效的排序和清理。 阅读建议:由于本资源涉及较多底层概念和技术细节,建议读者先复习C语言基础知识,特别是指针和内存管理部分。在学习过程中,可以尝试动手编写类似的代码片段,以便更好地理解和掌握文中所介绍的各种技巧。同时,注意观察代码注释,它们对于理解复杂逻辑非常有帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值