0

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

如果用户有焦点说txtbox1并且用户单击项目listbox,则应将所选项目文本设置为焦点textbox1

但就我而言,每当我点击 中的项目时listboxtxtbox1根本不会保持焦点。

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
            }

        }
    }
4

1 回答 1

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

希望这有帮助。

于 2013-03-12T07:58:38.103 回答