【问题标题】:Add item to listbox and select it将项目添加到列表框并选择它
【发布时间】:2016-09-05 10:47:34
【问题描述】:

我有一个列表框(SelectionMode 设置为MultiExtended,如this topic 所述)包含一个条目:"..."。当用户双击它时,会出现一个对话框来选择一个文件。当用户选择一个对话框消失并且文件应该被添加到列表中。这一切都有效。

我的问题是我只想选择列表框中新添加的条目。但是,使用以下代码 - "..." 和实际文件都被选中:

private void lbx_DoubleClick(object sender, EventArgs e)
{
    if (this.lbx.SelectedItem == "..."
            && this.ofdReferences.ShowDialog() == DialogResult.OK
    {
        this.lbx.Items.Insert(this.lbx.SelectedIndex, this.ofdReferences.FileName);
        this.lbx.SetSelected(this.lbx.SelectedIndex - 1, true); // select newly added entry
    }
}

所以我也添加了这一行:

this.lbx.SetSelected(this.lbx.SelectedIndex, false);        // unselect ...

现在选择了"..."-entry 而不是文件。

我什至尝试使用SelectedIndex = this.lbxProjectReferences.SelectedIndex - 1。这也会选择列表中的两个条目。

【问题讨论】:

  • 为什么不使用 lbx.selectedIndex 来设置选择?

标签: c# winforms listbox


【解决方案1】:

SelectedIndex-属性用于单选列表。但是我们可以在多列表中使用它,也可以在双击事件中使用,因为双击会隐含地选择一个单独的项目来正确设置SelecteItem

所以我使用了这种方法,删除选定条目的列表并仅添加我感兴趣的条目。

this.lbx.Items.Insert(this.lbx.SelectedIndex, this.ofdReferences.FileName);
var idx = this.lbx.SelectedIndex;
this.lbx.SelectedIndices.Clear();
this.lbx.SelectedIndices.Add(idx - 1); 

【讨论】:

    猜你喜欢
    • 2014-06-03
    • 2012-11-29
    • 1970-01-01
    • 2016-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-21
    相关资源
    最近更新 更多