Display different numbers in a textBox

故事扮演 提交于 2019-12-13 11:09:21

问题


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++) ;
        }
    }
}

回答1:


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




回答2:


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++) ;
    {

    }
 }



回答3:


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.



来源:https://stackoverflow.com/questions/52502780/display-different-numbers-in-a-textbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!