标签控件不显示在for循环中c#

时间:2015-08-19 04:29:58

标签: c# winforms foreach

我是编程世界的新手,请保持温和,我的问题是为什么标签控件在为每个循环调用时不会逐个显示文件名。我的任务是读取包含更多文件的文件夹,我需要读取文件名并在标签控件中显示,但它对我来说效果不好,对我来说很简单,但我是初学者为什么我不知道找到如何找出错误?

请找到代码。

namespace ImageScanning
{
    partial class Form1
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.label1 = new System.Windows.Forms.Label();
            this.button1 = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(21, 79);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(81, 13);
            this.label1.TabIndex = 0;
            this.label1.Text = "File scanning-->";
            // 
            // button1
            // 
            this.button1.Location = new System.Drawing.Point(27, 144);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(75, 23);
            this.button1.TabIndex = 1;
            this.button1.Text = "button1";
            this.button1.UseVisualStyleBackColor = true;
            this.button1.Click += new System.EventHandler(this.button1_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(284, 262);
            this.Controls.Add(this.button1);
            this.Controls.Add(this.label1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Button button1;
    }
}

按钮点击事件是:

private void button1_Click(object sender, EventArgs e)
{
     string imageloc = @"D:\Image";
     string[] files = Directory.GetFiles(imageloc);
     foreach (string file in files)
     {
          System.Threading.Thread.Sleep(1000);
          label1.Text = "File Scanning--> " + file;
          System.Threading.Thread.Sleep(3000);
          label1.Text = "";
     } 
}

2 个答案:

答案 0 :(得分:2)

你需要使用线程,在运行循环迭代时,UI线程很忙,UI部分在反映更改标签和其他UI控件之前等待事件完成,所以你需要启动另一个线程进行循环迭代然后UI线程可以自由更新UI。

试试这个

private void button1_Click(object sender, EventArgs e)
{
    Task.Factory.StartNew(() =>
    {
         string imageloc = @"D:\Image";
         string[] files = Directory.GetFiles(imageloc);
         foreach (string file in files)
         {
             System.Threading.Thread.Sleep(1000);
             // Any UI control which you want to use within thread,
             // you need Invoke using UI thread. I have declare a method below

             ExecuteSecure(() => label1.Text = "File Scanning--> " + file);
             System.Threading.Thread.Sleep(3000);
             ExecuteSecure(() => label1.Text = "");    
         }          
    });        
}    

//---
private void ExecuteSecure(Action action)
{
    if (InvokeRequired)
    {
        Invoke(new MethodInvoker(() => action()));
    }
    else
    {
        action();
    }
}

答案 1 :(得分:0)

以下是使用后台工作进程的示例代码

BackgroundWorker bw = new BackgroundWorker();
public Form1()
{
    InitializeComponent();

    bw.WorkerReportsProgress = true;
    bw.DoWork += bw_DoWork;
    bw.ProgressChanged += bw_ProgressChanged;
}

void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
   label1.Text = "File Scanning --> " + e.UserState as string;     
}

void bw_DoWork(object sender, DoWorkEventArgs e)
{
    string imageloc = @"D:\Image";
    string[] files = Directory.GetFiles(imageloc);
    foreach (var item in files)
    {
       bw.ReportProgress(0, item);
       Thread.Sleep(1000);
    }
 }

protected void button1_Click(object sender, EventArgs e)
{
   if (!bw.IsBusy)
   {
       bw.RunWorkerAsync();
   }
}