InvalidArgument=Value of ‘0’ is not valid for ‘SelectedIndex’
By Tan Lee Published on Mar 04, 2025 109
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 settingSelectedIndex
.
This approach ensures your ComboBox
doesn't attempt to select an item when none exist, preventing the exception.
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization