First of all, I apologize that I can not present code. The problem is the following in an asp.net webforms application, I have 2 listboxes and each one has the SelectedIndexChanged event, (the code inside those events is simply to move an item from one list to the other and vice versa) which are handled when there is PostBack and when some element is selected. I have 1 simple button with the click event but without code, let's say that it simply serves to do PostBack. Now, the problem arises because I have another button which activates another event but if I have an item selected from any of the listboxes, what is executed is first the SelectedIndexChanged event and then the event called by the second button and in reality I only want the event of the second button to be executed, can I explain? How could I avoid this?
As you can see in this example image, if I click on the Save button, having selected an item from the listbox on the left, what the application does is call the SelectedIndexChanged event of that listbox and only after that it calls the event of Save, and this works like this because of the PostBack issue. Is there a good way to implement that avoids that?
The problem is that you are not putting the code in the correct event handler.
As you explain, you are putting code in the SelectedIndexChanged event of the ListBox that you want to be executed when you click on a certain button if there is an item selected in the ListBox.
If you want the code to be executed when a certain button is clicked, the logical thing is that said code is in the handler of the button's click event.
If, on the other hand, you wanted to have code that would be executed every time the user selects a different option in the ListBox, what you would do is set the ListBox's AutoPostBack property to true and use its SelectedIndexChanged event.
I understand that in your case we are in the first scenario. So you should remove the SelectedIndexChanged event handler and include the code in the button's Click event handler to check that there is something selected in the ListBox.
We are in this scenario:
Clicking on the button executes the SelectedIndexChanged method and then that of the button itself.
Check:
That the two ListBox have the PostBack active
That the OnLoad event does not call any of the SelectedIndexChanged events
That the OnClick event of the button mistakenly does not call one of the SelectedIndexChanged methods of the listboxes
You could make use of the Ajax extensions UpdatePanel control (which is already pre-installed in Visual Studio), and they are used to postback only the portion of the page they enclose, arrange your ListBox and UpdatePanel something like this:
I will explain you now:
See if the Page_Load event is calling the SelectedIndexChanged event or some method that is moving the selected item to the other list.
After the post-back, the Page_Load is executed first and then the button event (eg Button_Click ).
I hope it helps you!