我想编写一个在1
中显示数字10
到textBox
的代码。我编写了以下代码。但是很遗憾,10
中仅显示数字textBox
。我的代码有什么问题?谢谢。
public partial class Form1 : Form
{
int i,j;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
for (i = 1; i <= 10; i++)
{
textBox1.Text = Convert.ToString(i);
for (j = 0; j < 10000000; j++) ;
}
}
}
答案 0 :(得分:0)
textBox1.Text = Convert.ToString(i);
在每个循环中覆盖文本框文本。您想要:
textBox1.Text += Convert.ToString(i) + " ";
请注意,还有其他方法可以实现
答案 1 :(得分:0)
将文本框的默认值设置为0,然后在单击按钮时将其递增
private void button1_Click(object
sender, EventArgs e)
{
textBox1.Text = Convert.ToString(Convert.Int32(textBox1.Text)+1);
for (j = 0; j < 10000000; j++) ;
{
}
}
答案 2 :(得分:0)
您不应在GUI线程中工作。当您进行一些简单的工作(少量计算)时,就没有问题了。但是当您的工作比较孤独时,请将其移交给后台工作人员。
这是正确的方法:
using System;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
namespace BackgroundWorkerExample
{
public partial class Form1 : Form
{
private BackgroundWorker worker;
public Form1()
{
InitializeComponent();
this.worker = new BackgroundWorker();
this.worker.DoWork += Worker_DoWork;
this.worker.ProgressChanged += Worker_ProgressChanged;
this.worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
this.worker.WorkerReportsProgress = true;
}
private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) => this.button1.Enabled = true;
private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.textBox1.Text = e.ProgressPercentage.ToString();
}
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 10; i++)
{
this.worker.ReportProgress(i);
// do work
Thread.Sleep(1000);
}
}
private void button1_Click(object sender, EventArgs e)
{
this.button1.Enabled = false;
this.worker.RunWorkerAsync();
}
}
}
按钮(在操作开始之后)被禁用为无效。原因是为了防止尝试第二次执行后台线程。后台工作者结束后,该按钮将启用。