【问题标题】:Label from ProgressBar value does not appearProgressBar 值的标签未出现
【发布时间】:2019-05-17 01:25:50
【问题描述】:

我有一个用于执行 mysql SP 的 bucle 和进度条,并且对于多行文本框中的每一行都可以正常工作。所以,我添加了一个带有 ProgressBar 的标签。每个步骤的值,仅查看 0% 和 100% 但是!当我停止使用 MessageBox 进行处理时,标签会显示每个正确的值。我试过睡眠,定时器,但标签仍然不起作用。有人可以帮我吗?

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("");
}

这是一个用于 Windows 10/7 桌面的 C# Windows 窗体,IDE Visual Studio 2017 框架 4.5。

我希望标签显示从 0% 到 100% 的 INT 值

【问题讨论】:

    标签: c# .net winforms


    【解决方案1】:

    在消息循环运行时发生更新。您的代码阻塞了主消息循环。

    MessageBox()(它是实现 .NET 的 MessageBox.Show() 的 Win32 API 函数)运行模式消息循环。但是,让主消息循环运行几乎总是比模态循环更好。

    在现代版本的 C# 中,您可以使用 async+await 来允许消息循环在您等待数据库操作时运行。例如,您正在使用的 command.ExecuteNonQuery() 函数有一个等待版本。

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-11-01
      • 2018-04-25
      • 1970-01-01
      • 1970-01-01
      • 2020-02-06
      相关资源
      最近更新 更多