2010年11月6日星期六

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.


 

 



2010年11月2日星期二

My first blog on blogger

I will try to write down all the thought and learning of programming here. I'm gonna focus on Asp.net and C#.

Also, blogging is a way to improving my writing English.

2009年12月21日星期一

免费的虚幻3引擎其实不好用啊

摘要:看来是要停止对UDK的研究了,不太适合。对于这个所谓的免费UE3引擎,有几点感想,和大家分享一下。
内容:11月初,UDK免费发布的时候的确是很兴奋,正好赶上考虑是否继续使用Quest3D的时机。加上AI Implant号称可以结合UE3引擎,还以为可以一举解决N个困扰半年的问题。不过经过1个月学习,查找资料,发现还是不能很好的结合到Crowd Simulation这个问题中来。基于这一个多月的学习,对UDK这个免费发布的UE3引擎有几点想法。
首先就是资料的匮乏。虽然是免费提供给非商业的用途的人使用,但是其提供的文档几乎是少得可怜。官方的在线文档就是基本和简介没有区别,没有涉及到什么实质的问题。打个不怎么合适的比方,就好象PS这个软件,用中文版,基本每个按钮和选项的作用大家都知道,但实际上用说会使用PS,那还是差得很远啊。而且,有些文档都没有更新,是介绍以前老版本的。官网上有些链接都是红色的,表示必须要是付费用户才可以进入(就是购买了虚幻引擎的用户),感觉似乎这些链接里面会讲些东西。不过,话说回来,文档这个问题,在我们购买的Quest3D和AI Implant这里也类似,感

2009年12月2日星期三

UDK-用VS来制作一个简单的Game Mod

摘要:使用VS建立UnrealScript工程,用此工程来修改和编译script文件(即是生成一个game mod)。不需使用unreal frontend软件就可以编译.u文件。
开发环境:XP 64bit;VS 2008;UDK beta2;
其他需求:1. 安装了nFringe。可参考 这里。
2. 如果要用自制的UDK地图。可参考 这里。
实现:
首先用VS新建一个UnrealScript工程,名字可随意(这里叫MyFirstGame,如有更改,在稍后配置时自行做相应修改),但是路径必须是如下图(否则有可能出现编译后文件丢失的问题,具体后述)。同时去掉"Create directory for solution"的勾。

然后开始配置MyFirstGame的属性,具体如下:
General的配置:
Target Game: 选UE3 Mod。
UCC Path: C:UDKUDK-2009-11-2BinariesUDK.exe
Reference Source Path: C:UDKUDK-200