【问题标题】:c# listbox selectedItem not workingc# listbox selectedItem 不起作用
【发布时间】:2015-09-02 13:47:41
【问题描述】:

好的,我希望有人尝试这个并给我一个具体的工作答案。 我有一个包含项目的 ListBox 控件,并且我有一个 ListBox.SelectedIndexChanged 的​​事件处理程序。

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

在另一个函数中我有这个代码:

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

它确实会移动到下一个项目,但不会引发事件。

我也试过了,但没有引发事件

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

但在我实际点击列表框之前,列表框项目仍未复制到文本框中

【问题讨论】:

  • 你需要什么?/和与updateTextBox2()相关的邮政编码

标签: c# listbox selecteditem


【解决方案1】:

试试这个

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

如果您想通过其他方法引发事件,则需要使用

listBox1_SelectedIndexChanged(sender, e);

该事件仅在您调用它时自动引发。 你也可以只调用更新方法,我需要查看更多代码才能理解为什么它不起作用。

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

【讨论】:

    【解决方案2】:

    我不知道它是否适用于 ListBox,但我知道它适用于 ListView,因此值得一试。尝试像这样设置选择:

    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;
    

    这可能会触发事件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 2016-06-09
      • 2019-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多