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.


 

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
目标检测(Object Detection)是计算机视觉领域的一个核心问题,其主要任务是找出图像中所有感兴趣的目标(物体),并确定它们的类别和位置。以下是对目标检测的详细阐述: 一、基本概念 目标检测的任务是解决“在哪里?是什么?”的问题,即定位出图像中目标的位置并识别出目标的类别。由于各类物体具有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具挑战性的任务之一。 二、核心问题 目标检测涉及以下几个核心问题: 分类问题:判断图像中的目标属于哪个类别。 定位问题:确定目标在图像中的具体位置。 大小问题:目标可能具有不同的大小。 形状问题:目标可能具有不同的形状。 三、算法分类 基于深度学习的目标检测算法主要分为两大类: Two-stage算法:先进行区域生成(Region Proposal),生成有可能包含待检物体的预选框(Region Proposal),再通过卷积神经网络进行样本分类。常见的Two-stage算法包括R-CNN、Fast R-CNN、Faster R-CNN等。 One-stage算法:不用生成区域提议,直接在网络中提取特征来预测物体分类和位置。常见的One-stage算法包括YOLO系列(YOLOv1、YOLOv2、YOLOv3、YOLOv4、YOLOv5等)、SSD和RetinaNet等。 四、算法原理 以YOLO系列为例,YOLO将目标检测视为回归问题,将输入图像一次性划分为多个区域,直接在输出层预测边界框和类别概率。YOLO采用卷积网络来提取特征,使用全连接层来得到预测值。其网络结构通常包含多个卷积层和全连接层,通过卷积层提取图像特征,通过全连接层输出预测结果。 五、应用领域 目标检测技术已经广泛应用于各个领域,为人们的生活带来了极大的便利。以下是一些主要的应用领域: 安全监控:在商场、银行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值