asp.netgridviewselecteditemselectedindexchangedselectcommand

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?


Solution

  • 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());
    
    
                    }
    
    
                }