none
Changing Textbox.text not working RRS feed

  • Question

  • Hello,

    I'm trying to get a button, when pushed, to change the text in a text box, text an SQL connection, then display another message.

    So,

    1) button pressed

    2) textbox message reads "connecting to SQL"

    3) SQLconnectionreoutine run 

    4) textbox message changed accordingly

    the "5 sec" message is there for debugging only, and will not be staying.

    However, only the last message is displayed.

    I have tried SLEEP and a Stopwatch constructor, but the same thing happens.

            private void button1_Click(object sender, EventArgs e)
            {
                UserMsg.Clear();
                UserMsg.BackColor = Color.Orange;
                UserMsg.ForeColor = Color.Black;
                UserMsg.Text = "Connecting to SQL..."; <--- DOSN't DISPLAY
    
    
    
                Stopwatch sw = new Stopwatch(); // sw cotructor
                sw.Start(); // starts the stopwatch
                for (int i = 0; ; i++)
                {
                    if (i % 100000 == 0) // if in 100000th iteration (could be any other large number
                                         // depending on how often you want the time to be checked) 
                    {
                        sw.Stop(); // stop the time measurement
                        if (sw.ElapsedMilliseconds > 5000) // check if desired period of time has elapsed
                        {
                            break; // if more than 5000 milliseconds have passed, stop looping and return
                                   // to the existing code
                        }
                        else
                        {
                            sw.Start(); // if less than 5000 milliseconds have elapsed, continue looping
                                        // and resume time measurement
                        }
                    }
                }
    
                UserMsg.Text = "5 secs are up..."; <--- DOSN't DISPLAY
    
                using (SqlConnection connection = new SqlConnection(@"Data Source=" + SQLServer + ";Integrated Security=False;User ID=sa;Password=password;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False;Initial Catalog=" + databasename + ";"))
                {
                    try
                    {
                        connection.Open();
                        UserMsg.BackColor = Color.LimeGreen;
                        UserMsg.ForeColor = Color.White;
                        UserMsg.Text = "Connected to SQL...";
                        chkSQL.Visible = false;
                    }
                    catch (SqlException)
                    {
                        UserMsg.BackColor = Color.Red;
                        UserMsg.ForeColor = Color.White;
                        UserMsg.Text = "..Unable to Connect to SQL Server. close this application, review the Config file and fix.";
                        System.IO.File.AppendAllText(errorlogpath, "\t" + errormsg);
                        chkSQL.Visible = true;
                        return;
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
            }

    If I comment out the SQLconnection part, the "5 secs" message appears, but the preceding "connecting" message is never displayed.

    If I comment out the SQLConnect part and the stopwatch part (and the "5 secs" message, then the "connecting message is displayed).

    Please, can someone tell me the (probably obvious to everyone else) mistake I am making, and what I need to do to rectify?

    Many thanks in advance

    Tuesday, July 30, 2019 8:43 AM

Answers

  • Hi G-Oker, 

    Thank you for posting here.

    For your question, you find that only the last message is displayed.

    I make a test on my side, and use Task methods to avoid the problem.

    You can refer the following code:

            private void button1_Click(object sender, EventArgs e)
            {
                UserMsg.Clear();
                UserMsg.BackColor = Color.Orange;
                UserMsg.ForeColor = Color.Black;
                UserMsg.Text = "1 Connecting to SQL...";
    
                Task.Factory.StartNew(()=> 
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    while (true)
                    {
                        if (sw.ElapsedMilliseconds > 5000)
                        {
                            MessageBox.Show("5 seconds");
                            break;
                        }
                    }
                    sw.Stop();
                    string connstr = @"Data Source=...";
                    using (SqlConnection connection = new SqlConnection(connstr))
                    {
                        try
                        {
                            connection.Open();
                            UserMsg.Invoke(new Action(()=> 
                            {
                                UserMsg.BackColor = Color.LimeGreen;
                                UserMsg.ForeColor = Color.White;
                                UserMsg.Text = "2 Connected to SQL...";
                            }));
                            
                            //chkSQL.Visible = false;
                        }
                        catch (SqlException)
                        {
                            UserMsg.BackColor = Color.Red;
                            UserMsg.ForeColor = Color.White;
                            UserMsg.Text = "..Unable to Connect to SQL Server. close this application, review the Config file and fix.";
                            //System.IO.File.AppendAllText(errorlogpath, "\t" + errormsg);
                            //chkSQL.Visible = true;
                            return;
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                });
            }

    The first value of text in TexBox:

    The second value:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, July 31, 2019 7:42 AM
    Moderator

All replies

  • Hi,

    "Long running operations" like connection to a database, writing or reading a text file from disk, or accessing the network will block your User Interface. By default your program can only do one thing at the same time. If you set the text on a Label or TextBox, your application will redraw that part of the screen if it has the time to do it. If you set the Text property, and immediately after, execute a long running operation, your application will not have time to actually redraw.

    Most API's in .NET provide an asynchronous way of calling long running operation. You will find the same methods, but with the word Async in the end. So opening a connection to a database can use the connection.OpenAsync() method. These methods will create a background thread to actually perform the operations so that your User Interface will keep responsive (using multiple CPU's in your system).

    In order to use these async methods, you will need to add the async keyword to your method signature and use the await keyword for every Async method you call.

    https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/

    Kind regards,

    Johnny Hooyberghs


    Tuesday, July 30, 2019 8:52 AM
  • Hi G-Oker, 

    Thank you for posting here.

    For your question, you find that only the last message is displayed.

    I make a test on my side, and use Task methods to avoid the problem.

    You can refer the following code:

            private void button1_Click(object sender, EventArgs e)
            {
                UserMsg.Clear();
                UserMsg.BackColor = Color.Orange;
                UserMsg.ForeColor = Color.Black;
                UserMsg.Text = "1 Connecting to SQL...";
    
                Task.Factory.StartNew(()=> 
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    while (true)
                    {
                        if (sw.ElapsedMilliseconds > 5000)
                        {
                            MessageBox.Show("5 seconds");
                            break;
                        }
                    }
                    sw.Stop();
                    string connstr = @"Data Source=...";
                    using (SqlConnection connection = new SqlConnection(connstr))
                    {
                        try
                        {
                            connection.Open();
                            UserMsg.Invoke(new Action(()=> 
                            {
                                UserMsg.BackColor = Color.LimeGreen;
                                UserMsg.ForeColor = Color.White;
                                UserMsg.Text = "2 Connected to SQL...";
                            }));
                            
                            //chkSQL.Visible = false;
                        }
                        catch (SqlException)
                        {
                            UserMsg.BackColor = Color.Red;
                            UserMsg.ForeColor = Color.White;
                            UserMsg.Text = "..Unable to Connect to SQL Server. close this application, review the Config file and fix.";
                            //System.IO.File.AppendAllText(errorlogpath, "\t" + errormsg);
                            //chkSQL.Visible = true;
                            return;
                        }
                        finally
                        {
                            connection.Close();
                        }
                    }
                });
            }

    The first value of text in TexBox:

    The second value:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Wednesday, July 31, 2019 7:42 AM
    Moderator
  • Thank you  Xingyu. I had to make some changes to the to stop exceptions, IE 

    UserMsg.Invoke(new Action(() => UserMsg.BackColor = Color.Red));

    etc, but this works perfectly. :-)

    Wednesday, July 31, 2019 11:54 AM
  • Thanks Johnny, I will read this and amned the software in the next revision.
    Wednesday, July 31, 2019 11:55 AM