c#设置32个文本框值更改时的事件

时间:2014-08-10 17:32:48

标签: c# winforms events textbox windows-forms-designer

我有这个功能

public void calculateTotalFructiferous() { 
            totalFructiferous.Text = ....;
        }

我有32个文本框。我想在每个32的值发生变化时触发该函数。我搜索谷歌,我发现我必须使用事件downkey and upkey,但我不确定究竟是哪一个。加上我想如果有办法制作 这个调用是在一个不同的线程而不是windows窗体的线程。

1 个答案:

答案 0 :(得分:3)

对所有TextBox使用TextChanged事件:

    public Form1()
    {
        InitializeComponent();

        textBox1.TextChanged += TextChanged;
        textBox2.TextChanged += TextChanged;
    }


    private void TextChanged(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)sender;
        string text = tb.Text;

        calculateTotalFructiferous(text);
    }

    public void calculateTotalFructiferous(string text) 
    { 
        totalFructiferous.Text = ....;
    }
}

当你有CPU密集型计算时,你可以使用它:

public delegate void CalculateTotalFructiferousDelegate(string text);

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        textBox1.TextChanged += TextChanged;
        textBox2.TextChanged += TextChanged;
    }


    private void TextChanged(object sender, EventArgs e)
    {
        TextBox tb = (TextBox)sender;
        string text = tb.Text;

        //If it is a CPU intensive calculation
        Task.Factory.StartNew(() =>
        {
            //Do sometihing with text
            text = text.ToUpper();

            if (InvokeRequired)
                Invoke(new CalculateTotalFructiferousDelegate(calculateTotalFructiferous), text);
        });
    }

    public void calculateTotalFructiferous(string text)
    {
        totalFructiferous.Text = text;
    }
}