【问题标题】:c# set event when 32 textbox value changec#设置32文本框值变化时的事件
【发布时间】:2023-03-06 09:48:01
【问题描述】:

我有这个功能

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

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

【问题讨论】:

  • @FarhadJabiyev 这是我最喜欢的解决方案,但我的经理拒绝了
  • 为所有文本框添加一个TextChanged 监听器(可以使用相同的处理程序,并通过 sender 参数访问特定控件)。当发生变化时,调用相应的函数。如果首先将 TextBox 控件添加到 Collection 中(无论如何这可能是有益的),或者已经是同一容器的 [exclusive] 子级,则可以通过代码隐藏中的简单循环将处理程序添加到所有控件中。不要不要使用不同的线程。
  • @user2864740 你的意思是把我方法的参数改成object sender, EventArgs e 吗?我不知道你说的这个系列
  • 还要注意,TextBox等UI组件必须在UI线程中处理,否则会遇到非法跨线程调用等问题。

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


【解决方案1】:

对所有文本框使用 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;
    }
}

【讨论】:

  • 这就是我现在正在做的,但我认为这与表单线程在同一个线程中,对吧?
  • thread 这样的词不适合这么简单的事情。
  • @AnastasieLaurent 不要不要为此使用线程。鉴于问题描述,没有原因。
  • 如果“totalFructiferous”是一个 UI 控件,您需要将文本设置为与创建时相同的线程...
猜你喜欢
  • 1970-01-01
  • 2015-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-26
相关资源
最近更新 更多