简体   繁体   English

C#列表框selectedItem不起作用

[英]c# listbox selectedItem not working

Ok, I would like somebody to try this and give me a specific working answer. 好的,我想有人尝试一下,给我一个具体的工作答案。 I have a ListBox control that has items and I have an event handler for ListBox.SelectedIndexChanged. 我有一个包含项的ListBox控件,并且有一个ListBox.SelectedIndexChanged事件处理程序。

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    updateTextBox2(); //sets the selectedIndexItem to textbox2
}

In another function I have this code: 在另一个函数中,我有以下代码:

listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count;

It does move to the next item but it doesn't raise the event. 它确实移至下一个项目,但不会引发该事件。

I have also tried this without raising an event 我也尝试了这个没有引发事件

listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count;
updateTextBox2(); //

but the listbox item is still not copied into the textbox until I actual click on the listbox 但在我实际单击列表框之前,列表框项仍未复制到文本框中

Try this 尝试这个

    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        updateTextBox1(); 
    }

    private void updateTextBox1()
    {
        textBox1.Text = Convert.ToString(listBox1.SelectedIndex);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count;
        listBox1_SelectedIndexChanged(sender, e);
    }

if you are wanting to raise the event though another method, you need to use 如果您想通过另一种方法引发事件,则需要使用

listBox1_SelectedIndexChanged(sender, e);

the event is only raised automaticaly when you invoke it. 该事件仅在您调用它时自动引发。 Also you could just invoke the update method, id need to see more code to understand why it wouldn't work. 您也可以只调用update方法,id需要查看更多代码以了解为什么它不起作用。

private void button1_Click(object sender, EventArgs e)
    {
        listBox1.SelectedIndex = (listBox1.SelectedIndex + 1) % listBox1.Items.Count;
        updateTextBox1();
    }

I don't know if it works for ListBox, but I know it does for ListView so it's worth a shot. 我不知道它是否适用于ListBox,但我知道它适用于ListView,所以值得一试。 Try setting the selection like this instead: 尝试像这样设置选择:

listBox1.Items[listBox1.SelectedIndex].Selected = false; // Not 100% sure the Items have a Selected property
listBox1.Items[(listBox1.SelectedIndex + 1) % listBox1.Items.Count].Selected = true;

That might fire the event. 这可能会触发该事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM