Search code examples
c#windows-phone-7messagebox

Messagebox displaying too early - C#


I am just starting off with the world of programming C#, and have come across a small glitch in my code which causes the design to be ruined.

For some reason, when I am trying change the text in a textbox, it does not visually change until a messagebox has been displayed, which is underneath the code to change the text. I am programming for WP7, if that changed anything. It runs on a button click.

Below is my code:

 private void Draw()
    {
        Random random = new Random((int)DateTime.Now.Ticks);

        number[0] = random.Next(0, 9);
        number[1] = random.Next(0, 9);
        number[2] = random.Next(0, 9);

            no1.Text = number[0].ToString();
            no2.Text = number[1].ToString();
            no3.Text = number[2].ToString();

        MessageBox.show("Example message");

    }

Solution

  • As Russell Troywest pointed out, your code is executing on the UI thread, the very same thread that is in charge of updating the graphical interface. Therefore, the visual representation of the textbox won't be updated until your function exits.

    A simple solution is to delay the execution of your messagebox:

    this.Dispatcher.BeginInvoke(() => MessageBox.show("Example message"));
    

    This way, your draw method will exit without displaying the Message Box, then the UI thread will display it as soon as it's done refreshing the interface.