[英]Add item to listbox and select it
I have a listbox ( SelectionMode
is set to MultiExtended
as mentioned on this topic ) containing one single entry: "..."
. 我有一个列表框(如本主题中所述,将
SelectionMode
设置为MultiExtended
)包含一个条目: "..."
。 When user double-clicks this a dialog appears to select a single file. 当用户双击它时,将出现一个对话框以选择一个文件。 When user selects one the dialog disappears and the file should be added to the list.
当用户选择一个时,对话框消失,该文件应添加到列表中。 This all works.
所有这一切。
My problem is that I want to select only that newly added entry within my listbox . 我的问题是我只想在列表框中选择新添加的条目 。 However with the following code both - the
"..."
and the actual file are selected: 但是,通过以下代码,都选择了
"..."
和实际文件:
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
}
}
So I also added this line: 所以我也添加了这一行:
this.lbx.SetSelected(this.lbx.SelectedIndex, false); // unselect ...
Now the "..."
-entry is selected instead of the file. 现在,选择
"..."
条目而不是文件。
I even tried to use SelectedIndex = this.lbxProjectReferences.SelectedIndex - 1
. 我什至尝试使用
SelectedIndex = this.lbxProjectReferences.SelectedIndex - 1
。 This also selects both entries within the list. 这还将选择列表中的两个条目。
The SelectedIndex
-property is for single-select-lists. SelectedIndex
属性适用于单选列表。 However we can use it on multi-lists also within a double-click-events also because a double-click will implicetly select one single item setting the SelecteItem
correctly. 但是,我们也可以在双击事件中在多列表上使用它,因为双击将隐式选择一个正确设置
SelecteItem
项目。
So I used this approach that deletes the list of selected entries and adds only that entry I´m interested in. 因此,我使用了这种方法,即删除所选条目的列表,而仅添加我感兴趣的条目。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.