Home » Asp.net

GridView SelectedIndexChanged Problem



I have a GridView with a TemplateField where I'm hosting a button. The button has an event hanlder OnClick, so when it is clicked it will execute some code.

The problem I'm having is that when I click the button in a row, the Button event handler is not excecuted right away. Instead, the GridView selectedIndexChanged is fired and then I need to click my button again to fire the button's event handler.

So, is there a way I could know if the button or the row was clicked  in the GridView SelectedIdexChanged event? And why the Button's event handler is not firering right away?


Thank you so much!



1 Answer Found


Answer 1

That is event  bubbling and you can get more info about that here.

If you have a Template Field like this

<asp:Button ID="button1" runat="server" Text="Submit" CommandName="Select" 
OnClick="btnSubmit_Click" />

when you click  the button, button  OnClick event fires and then SelectedIndexChanged (as command name was set to Select) and finally row  Command Event.

protected void btnSubmit_Click(object sender, EventArgs e)
//Button Click event            
protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
//GridView Selected Index Changed event
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
//Get the row clicked
int rowIndex = Convert.ToInt32(e.CommandArgument);
//Row Command
switch (e.CommandName)
case "Something":
case "Select":
case "Delete":

So, make sure that you are using only Row Command event by setting CommandName to something else other than Select. You do not need that button click event also.



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure