I want to write a code that displays numbers 1
to 10
in a textBox
. Following code has been written by me. But unfortunately only number 10
is displayed in textBox
. What is wrong in my code? Thanks.
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++) ;
}
}
}
textBox1.Text = Convert.ToString(i);
Overwrites the textbox text each loop. You want:
textBox1.Text += Convert.ToString(i) + " ";
Note, there are others ways of doing this
Set default value of text box to 0 and then just increment it on button click
private void button1_Click(object
sender, EventArgs e)
{
textBox1.Text = Convert.ToString(Convert.Int32(textBox1.Text)+1);
for (j = 0; j < 10000000; j++) ;
{
}
}
You should not do work in GUI thread. When you have some simple work (small calculation), then there is not a problem. But when you have a loner work, move the work to background worker.
This is the correct way how to do this:
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();
}
}
}
The button (after the operation starts) is disabled to be inactive. The reason is, to prevent try second execution of the background thread. When the background worker ends, the button is enabled.