Question Show the messagebox again

teymoorei

Active member
Joined
Jan 11, 2012
Messages
36
Programming Experience
1-3
Why is the message displayed twice?

this is code :

VB.NET:
    Private Sub TabControl2_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl2.SelectedIndexChanged
        If txtName.Text = Nothing Then
            TabControl2.SelectedIndex = 0
            MessageBox.Show("برای نمایش و جستجوی بار ابتدا باید مشتری را انتخاب نمایید", "توجه", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.RightAlign)
            Exit Sub
        End If
    End Sub
 
If txtName is empty and tabpage2 is selected or TabControl2.SelectedIndex = 1 is selected, it returns to tabpage1 with TabControl2.SelectedIndex = 0 or TabControl2.SelectedIndex = 0 is selected and it sends a message but displays the message twice.
 
Teymoorei,

If you use the debugger and step through the code one line at a time it will become clear which line of code is triggering each TabControl2_SelectedIndexChanged event. You can then modify accordingly
 
It's like you didn't even read what I posted. If I ask a question, it's not for my health. I ask it so you will answer it. I asked:
What happens when you change the `SelectedIndex`?
If you had taken the time to think about that, as was my intention, then you'd already see the problem. It should be obvious that what happens is that the SelectedIndexChange event is raised. If you raise the SelectedIndexChange event when the SelectedIndexChange event is raised then that means that it is raised twice, so your event handler is executed twice. If you display a message in a method that is executed twice, how many times would you expect your message to be displayed?

You need to put some thought into the logic your code needs to follow, then write code to actually implement that logic. If you only want the message displayed under specific circumstances then you need to write code to detect those circumstances. If you don't want the message displayed if the Selectedindex is zero then write code to detect that.
 
Back
Top