ComboBox.SelectedIndex Property
Gets or sets the index specifying the currently selected item.
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
| Exception | Condition |
|---|---|
| ArgumentOutOfRangeException |
The specified index is less than or equal to -2. -or- The specified index is greater than or equal to the number of items in the combo box. |
This property indicates the zero-based index of the currently selected item in the combo box list. Setting a new index raises the SelectedIndexChanged event.
SelectedIndex , SelectedValue, and FormattingEnabled are related as follows:
-
If FormattingEnabled is false, SelectedIndex will not be set to -1 when SelectedValue is blank.
-
If FormattingEnabled is true, SelectedIndex will be set to -1 when SelectedValue is blank.
Note:
|
|---|
|
To deselect the currently selected item, set the SelectedIndex to -1. You cannot set the SelectedIndex of a ComboBox item to -1 if the item is a data-bound item. |
The following code example show how to use the FindString method and SelectedIndex property. The example is part of a complete example in the ComboBox class overview.
Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC
The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
DataTabledtFruit =newDataTable("FruitTable");
//define columns
DataColumncolID =newDataColumn();
colID.DataType=typeof(Int32);//VB.NET GetType(Int32)
colID.ColumnName="ID";
DataColumncolDesc =newDataColumn();
colDesc.DataType=typeof(String);
colDesc.ColumnName="Description";
//add columns to table
dtFruit.Columns.AddRange(newDataColumn[]{colID,colDesc });
//add rows
DataRowrow =dtFruit.NewRow();
row[colID]=1;row[colDesc]="Apples";
dtFruit.Rows.Add(row);
row =dtFruit.NewRow();
row[colID]=1;row[colDesc]="Bananas";
dtFruit.Rows.Add(row);
row =dtFruit.NewRow();
row[colID]=1;row[colDesc]="Oranges";
dtFruit.Rows.Add(row);
//add extra blank row.
DataRowViewdrv =dtFruit.DefaultView.AddNew();
drv.EndEdit();
//Bind combo box
DataViewdv =newDataView(dtFruit);
dv.Sort="ID ASC";//ensure blank item on top
cboFruit.DataSource=dv;
cboFruit.DisplayMember="Description";
cboFruit.ValueMember="ID";
}
private void UnselectComboMethod(){
if(cboFruit.SelectedIndex>0)
{
cboFruit.SelectedIndex=0;
}
else
{
MessageBox.Show("no fruit selected");
}
}
Note: