c# InvalidArgument=“-1”的值对于“index”无效

Cel*_*itz 2 c# validation winforms

我有一个 cmbPlace(组合框),它的项目自动填充了 System.IO 驱动器(C:\、D:\ 等)。同时它也有验证事件。代码如下:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我尝试测试验证 errormessage1 和 cmbPlace.Focus() (如输入“null”或“不在索引中”文本)时,它们不会触发并显示错误

InvalidArgument=“-1”值对于“索引”无效。参数名称:索引

这是导致错误的行/代码,在ValidatePlacecmbPlace_Validating

if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)
Run Code Online (Sandbox Code Playgroud)

Zei*_*kki 5

正如我在评论中发布的,当没有选择任何项目时,SelectedIndex属性返回 -1,这是通过索引访问数组元素的无效索引(使用cmbPlace.Items[m])。也就是说,您需要在访问所选元素之前进行检查:

if(cmbPlace.SelectedIndex >= 0)
{
   // do something
}
else
{
  // No item selected, handle that or return
}
Run Code Online (Sandbox Code Playgroud)