Сделайте элемент управления динамически распознать другого - PullRequest
0 голосов
/ 09 марта 2012

У меня есть приложение Windows Form, где я создал динамические элементы управления, и мне нужны программные события, такие как Keypress, но я не могу этого сделать, потому что они не знают друг друга, когда они просто существуют во время выполнения.(Извините, английский от Google Tradutor)

Ответы [ 2 ]

0 голосов
/ 10 марта 2012

Похоже, проблема в том, что вы создаете свои динамические переменные локально:

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

    }
}
0 голосов
/ 09 марта 2012

Вы можете попробовать следующий код:

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

Это должно работать.

...