Celcius_Bitz Celcius_Bitz - 1 month ago 9
C# Question

c# InvalidArgument=Value of '-1' is not valid for 'index'

I have a cmbPlace(combobox) which it's item filled automatically with System.IO Drives(C:\, D:\, etc). while it's also have validating events. Code below:

using System.IO;
public FNamefile()
{
InitializeComponent();
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
cmbPlace.Items.Add(d.Name);
}
}

private void FNamefile_Load(object sender, EventArgs e)
{
errorProvider1.ContainerControl = this;
}

private bool ValidatePlace()
{
bool bStatus = true;
int m = cmbPlace.SelectedIndex;
if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)
{
errorProvider1.SetError(cmbPlace, "");
}
else if (cmbPlace.Text == "" || (cmbPlace.Items[m]).ToString() != cmbPlace.Text)
{
errorProvider1.SetError(cmbPlace, "Please enter a valid location");
bStatus = false;
}
return bStatus;
}
private void cmbPlace_Validating(object sender, CancelEventArgs e)
{
ValidatePlace();
int m = cmbPlace.SelectedIndex;

if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)
{ }
else
{
cmbPlace.Focus();
}
}


The problem is when I tried to test the validating errormessage1 and cmbPlace.Focus() like input 'null' or 'not in index' text, they won't trigger and show error


InvalidArgument=Value of '-1' is not valid for 'index'. Parameter name: index


here's the line/code that cause error, in
ValidatePlace
and
cmbPlace_Validating


if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)

Answer

As I posted in the comments, when no item is selected the SelectedIndex Property returns -1 which is a invalid index for the accessing an array element by index (using cmbPlace.Items[m]). Saying that, you need to check before accessing the selected element:

if(cmbPlace.SelectedIndex >= 0)
{
   // do something
}
else
{
  // No item selected, handle that or return
}
Comments