Diego Pachas
Diego Pachas

Reputation: 11

Label from ProgressBar value does not appear

I have a bucle and progressbar for execute mysql SP and work's fine for each line from a multiline textbox. So, I added a label with a ProgressBar. Value for each step and only view 0% and 100% BUT! When I stop processing with a MessageBox, the label shows me each correct value. I tried sleep, timer and still the label does not work. Can someone help me?

foreach (string line in lines)
{
    if (line != "" && estado < 9)
    {
        pms[0].Value = line.Substring(4, line.Length - 4);
        pms[1].Value = estado;
        pms[2].Value = Global.Mid;
        pms[3].Value = "1";
        MySqlCommand command = new MySqlCommand
        {
            Connection = connection,
            CommandType = CommandType.StoredProcedure,
            CommandText = tipo
        };
        command.Parameters.AddRange(pms);
        connection.Open();
        if (command.ExecuteNonQuery() == 1)
        {
            ok++;
            log.WriteLine("Change,{0},{1}", line, estado);
            lines[progressBar1.Value] = "A>" + line;
            BoxList.Lines = lines;
        }
        else
        {
            ko++;
            log.WriteLine("Error,{0},{1}", line, estado);
        }
        connection.Close();
    }
    progressBar1.Increment(1);
    label2.Text = "Completado " +(progressBar1.Value * 100 / lines.Length).ToString() + "%";
    //MessageBox.Show("");
}

This is a C# windows form for a Windows 10/7 desktop, IDE visual studio 2017 with framework 4.5.

I expect the label show me INT values from 0% to 100%

Upvotes: 1

Views: 52

Answers (1)

Ben Voigt
Ben Voigt

Reputation: 283803

Updates happen when the message loop is running. Your code is blocking the main message loop.

MessageBox() (which is the Win32 API function that implements .NET's MessageBox.Show()) operates a modal message loop. However, it's almost always better to get the main message loop running than a modal one.

In modern versions of C#, you can use async+await to allow the message loop to run while you're waiting for database actions. For example, there's an awaitable version of that command.ExecuteNonQuery() function you are using.

Upvotes: 3

Related Questions