使一个控件动态识别另一个控件

本文关键字:控件 动态 识别 另一个 一个 | 更新日期: 2023-09-27 18:27:14

我有一个应用程序Windows窗体,我在其中创建了动态控件,我需要像Keypress这样的程序事件,但我做不到,因为一旦它们在运行时存在,它们就不认识了。(对不起:谷歌Tradutor英文版)

使一个控件动态识别另一个控件

问题似乎是您正在本地创建动态变量:

ComboBox c1 = new Combobox(); 
TextBox t1 = new TextBox();

把jacqijvv的答案改一点,看起来更像我相信你正在努力实现的目标。我还假设您有多个彼此相关的文本框/组合框对,因此您可以将它们存储在字典对象中,以便稍后在事件处理程序中检索它们:

public partial class Form1 : Form
{
    public Dictionary<TextBox, ComboBox> _relatedComboBoxes;
    public Dictionary<ComboBox, TextBox> _relatedTextBoxes;
    public Form1()
    {
        InitializeComponent();
        _relatedComboBoxes = new Dictionary<TextBox, ComboBox>();
        _relatedTextBoxes = new Dictionary<ComboBox, TextBox>();
        TextBox textBox = new TextBox();
        textBox.Text = "Button1";
        textBox.KeyDown += textBox_KeyDown;
        ComboBox comboBox = new ComboBox();
        // todo: initialize combobox....
        comboBox.SelectedIndexChanged += comboBox_SelectedIndexChanged;

        // add our pair of controls to the Dictionaries so that we can later
        // retrieve them together in the event handlers
        _relatedComboBoxes.Add(textBox, comboBox);
        _relatedTextBoxes.Add(comboBox, textBox);
        // add to window
        this.Controls.Add(comboBox);
        this.Controls.Add(textBox);
    }
    void comboBox_SelectedIndexChanged(object sender, EventArgs e)
    {
        ComboBox comboBox = sender as ComboBox;
        TextBox textBox = _relatedTextBoxes[comboBox];
        // todo: do work
    }
    void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        // find the related combobox
        ComboBox comboBox = _relatedComboBoxes[textBox];
        // todo: do your work
    }
}

您可以尝试以下代码:

public partial class Form1 : Form
{
    // Create an instance of the button
    TextBox test = new TextBox();
    public Form1()
    {
        InitializeComponent();
        // Set button values
        test.Text = "Button";
        // Add the event handler
        test.KeyPress += new KeyPressEventHandler(this.KeyPressEvent);
        // Add the textbox to the form
        this.Controls.Add(test);
    }

    // Keypress event
    private void KeyPressEvent(object sender, KeyPressEventArgs e)
    {
        MessageBox.Show(test.Text);
    }
}

这应该行得通。