使控件动态识别另一个

时间:2012-03-09 19:19:39

标签: c# winforms dynamic

我有一个应用程序Windows窗体,我创建了动态控件,我需要像Keypress这样的程序事件,但我无法做到这一点,因为一旦它们只是在运行时存在就不会彼此了解。 (我很抱歉:谷歌Tradutor的英语)

2 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

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

这应该有效。

答案 1 :(得分:0)

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

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

    }
}