InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’

By Tan Lee Published on Mar 04, 2025  109
You might encounter the following error when setting the SelectedIndex of a ComboBox:
cbOptions.DataSource = GetData();
cbOptions.SelectedIndex = 0;

However, you encounter the following exception:

System.ArgumentOutOfRangeException: 'InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’. (Parameter ‘value’)
Actual value was 0.'

This error occurs because the DataSource you are binding to is empty. The SelectedIndex property can only be set if the ComboBox contains items.

Solution

1. Expecting Data to Always Be Available?

If your application assumes that the DataSource always contains data, then the real issue is not the exception—it’s the empty data source. You should investigate why GetData() is returning no data.

2. Handling Cases Where No Data Exists

If it’s acceptable for the data source to sometimes be empty (e.g., when fetching data dynamically), you should check for data before setting SelectedIndex.

Fixed Code:

var data = GetData();

if (data.Any()) 
{
    cbOptions.DataSource = data;
    cbOptions.SelectedIndex = 0;
}
else 
{
    cbOptions.DataSource = null; // Optional: Clear previous data
}

In this example:

  • If the DataSource should never be empty, debug why it is.
  • If an empty DataSource is acceptable, check before setting SelectedIndex.

This approach ensures your ComboBox doesn't attempt to select an item when none exist, preventing the exception.