tags:

views:

1059

answers:

3

In ASP.NET, if I databind a gridview with a array of objects lets say , how can I retrieve and use foo(index) when the user selects the row?

i.e.

dim fooArr() as foo;
gv1.datasource =  fooArr;
gv1.databind();

On Row Select

Private Sub gv1_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gv1.RowCommand

        If e.CommandName = "Select" Then
            'get and use foo(index)    
        End If
    End Sub
A: 

in theory the index of the row, should be the index of foo (maybe +1 for header row, you'll need to test). so, you should be able to do something along these lines

dim x as object = foo(e.row.selectedIndex)

The other alternative is to find a way to databind the index to the commandArgument attribute of the button.

Stephen Wrighton
A: 

There's probably a cleaner way of doing this, but you could set the CommandArgument property of the row to its index. Then something like foo(CInt(e.CommandArgument)) would do the trick.

kristian
+1  A: 

If you can be sure the order of items in your data source has not changed, you can use the CommandArgument property of the CommandEventArgs.

A more robust method, however,is to use the DataKeys/SelectedDataKey properties of the GridView. The only caveat is that your command must be of type "Select" (so, by default RowCommand will not have access to the DataKey).

Assuming you have some uniqueness in the entities comprising your list, you can set one or more key property names in the GridView's DataKeys property. When the selected item in the GridView is set, you can retrieve your key value(s) and locate the item in your bound list. This method gets you out of the problem of having the ordinal position in the GridView not matching the ordinal position of your element in the data source.

Example:

<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="True" 
    DataKeyNames="Name" onrowcommand="GridView1_RowCommand1" 
    onselectedindexchanged="GridView1_SelectedIndexChanged">
</asp:GridView>

Then the code-behind (or inline) for the Page would be something like:

protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
{
   // Value is the Name property of the selected row's bound object.
   string foo = GridView1.SelectedDataKey.Value as string; 
}

Another choice would be to go spelunking in the Rows collection of the GridView, fetching values a column at a time by getting control values, but that's not recommended unless you have to.

Hope this helps.

Jared