ListBox.SelectedItem 属性 (System.Windows.Forms)

ListBox.SelectedItem 属性 (System.Windows.Forms)

获取或设置当前选定的项。ListBox

public:

property System::Object ^ SelectedItem { System::Object ^ get(); void set(System::Object ^ value); };

[System.ComponentModel.Bindable(true)]

[System.ComponentModel.Browsable(false)]

public object SelectedItem { get; set; }

[System.ComponentModel.Bindable(true)]

[System.ComponentModel.Browsable(false)]

public object? SelectedItem { get; set; }

[]

[]

member this.SelectedItem : obj with get, set

Public Property SelectedItem As Object

属性值

Object

一个对象,表示控件中的当前选定内容。

属性

BindableAttribute

BrowsableAttribute

示例

下面的代码示例演示如何使用 SelectedIndexChanged 事件来搜索和选择其他 ListBox 控件中的项。 该示例使用 SelectedIndexChanged 事件来确定何时更改了所选项 ListBox 。 然后,示例代码使用SelectedItem属性读取项的文本,并使用第一FindString个返回ListBox的文本对其他SelectedItem方法调用ListBox该方法。 如果在另 ListBox一个项中找到某个项,则选择该项。 此示例要求已将两 ListBox 个控件命名 listBox1 和 listBox2已添加到窗体中,并且这两 ListBox 个控件都包含相同的项。 该示例还要求在示例中定义的事件处理方法连接到 SelectedIndexChanged 事件 listBox1。

private:

void listBox1_SelectedIndexChanged( Object^ /*sender*/, System::EventArgs^ /*e*/ )

{

// Get the currently selected item in the ListBox.

String^ curItem = listBox1->SelectedItem->ToString();

// Find the string in ListBox2.

int index = listBox2->FindString( curItem );

// If the item was not found in ListBox 2 display a message box,

// otherwise select it in ListBox2.

if ( index == -1 )

MessageBox::Show( "Item is not available in ListBox2" );

else

listBox2->SetSelected( index, true );

}

private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)

{

// Get the currently selected item in the ListBox.

string curItem = listBox1.SelectedItem.ToString();

// Find the string in ListBox2.

int index = listBox2.FindString(curItem);

// If the item was not found in ListBox 2 display a message box, otherwise select it in ListBox2.

if(index == -1)

MessageBox.Show("Item is not available in ListBox2");

else

listBox2.SetSelected(index,true);

}

Private Sub listBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles listBox1.SelectedIndexChanged

' Get the currently selected item in the ListBox.

Dim curItem As String = listBox1.SelectedItem.ToString()

' Find the string in ListBox2.

Dim index As Integer = listBox2.FindString(curItem)

' If the item was not found in ListBox 2 display a message box, otherwise select it in ListBox2.

If index = -1 Then

MessageBox.Show("Item is not available in ListBox2")

Else

listBox2.SetSelected(index, True)

End If

End Sub

注解

对于标准ListBox,可以使用此属性来确定在哪个项中选择。ListBox 如果属性SelectionModeListBox设置为任SelectionMode.MultiSimple一或SelectionMode.MultiExtended(指示多选ListBox)且列表中选择了多个项,则此属性可以返回任何选定的项。

若要检索包含多重选择 ListBox中所有选定项的集合,请使用该 SelectedItems 属性。 如果要获取当前选定项的索引位置, ListBox请使用该 SelectedIndex 属性。 此外,可以使用 SelectedIndices 该属性获取多重选择 ListBox中的所有选定索引。

适用于