Diogo Cardoso
Diogo Cardoso

Reputation: 22257

How to get selected item in ASP.NET GridView

How can I get the selected item on the SelectedIndexChanging handler when using two SelectCommands? I can get the selected row through e.SelectedRow but I'm unable to get the selected column.

It's correct to have more than one SelectCommand in a GridView? If not, what's the best way?

Upvotes: 2

Views: 3747

Answers (2)

scartag
scartag

Reputation: 17680

You don't have to use select commands. you can use template fields and add a named command to it then you can check which of them was clicked in the RowCommand event (and u can also get the row index as well) see below.

  <asp:TemplateField ShowHeader="False">
            <ItemTemplate>
                <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="false" 
                    CommandName="MyCommand" Text="Button" CommandArgument='<%# Container.DataItemIndex %>'></asp:LinkButton>
            </ItemTemplate>
        </asp:TemplateField>

RowCommend Event below

 protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
            {
                if(e.CommandName.Equals("MyCommand"))
                {
                    int row = Int32.Parse(e.CommandArgument.ToString());


                }


            }

Upvotes: 3

GunnerL3510
GunnerL3510

Reputation: 715

You don't select a column in a gridview, you select a row. If you want a particular field of a row to be "selectable" you might consider using a HyperLinkField or a ButtonField and handle the events for that. But to my knowledge, admittedly it's limited, there is no way to be able to know, purely with a GridView and its SelectedRow Property which field in the row was "selected" when the row was selected.

Upvotes: 4

Related Questions