ArgumentOutOfRangeException: InvalidArgument=Value of 0 is not valid for SelectedIndex

Problem

Let’s say you’re initializing a ComboBox like this:

cbOptions.DataSource = GetData(); cbOptions.SelectedIndex = 0;

And you get the following exception:

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

You’re getting this exception because the DataSource is empty.

Solution

Are you expecting there to always be data?

If you’re expecting there to always be data, and the DataSource is empty, then you need to troubleshoot why it’s empty. This ArgumentOutOfRangeException is not really your problem, the empty DataSource is your problem.

Or is it acceptable that there’s no data sometimes?

If you’re getting data dynamically, like from a database, and it’s possible there’s no data available, then you’ll need to check if there’s data before setting SelectedIndex.

var data = GetData(); if (data.Any()) { cbOptions.DataSource = data; cbOptions.SelectedIndex = 0; }

Leave a Comment