将值设置为以winforms为焦点的文本框

时间:2013-03-12 07:45:10

标签: c# winforms

我有一个listbox控件和三个textbox表格

如果用户专注于说txtbox1并且用户点击listbox中的项目,则应将所选项目文本设置为焦点textbox1

但在我的情况下,每当我点击listbox中的项目时,txtbox1根本不会保持焦点。

private void lstFields_MouseClick(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Left)
        {
            ListBoxControl ListBox = (ListBoxControl)sender;
            int itemIndex = ListBox.IndexFromPoint(e.Location);
            if (itemIndex == -1)
            {
                lstFields.SelectedIndex = -1;
                return;
            }
            else
            {
                //Here I need that focused textbox to set value
            }

        }
    }

1 个答案:

答案 0 :(得分:3)

试试这个,这可行

private TextBox lastFocused;

private void Form1_Load(object sender, EventArgs e)
    {
        foreach (var box in Controls.OfType<TextBox>())
        {
            box.LostFocus += textBoxFocusLost;
        }
    }


private void textBoxFocusLost(object sender, EventArgs e)
{
    lastFocused = (TextBox)sender;
}

然后

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (lastFocused != null)
        {
            lastFocused.Text = listBox1.SelectedItem.ToString();
        }
    }
希望这有帮助。