c#InvalidArgument=的值'-1';对';无效;指数';

c#InvalidArgument=的值'-1';对';无效;指数';,c#,winforms,validation,C#,Winforms,Validation,我有一个cmbPlace(组合框),它的项目会自动填充System.IO驱动器(C:\、D:\,等等)。同时它也有验证事件。代码如下: using System.IO; public FNamefile() { InitializeComponent(); DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { cmbPlace.Item

我有一个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();
    }
}
问题是,当我尝试测试validating errormessage1和cmbPlace.Focus()时,比如输入“null”或“not in index”文本,它们不会触发并显示错误

InvalidArgument=值'-1'对'index'无效。参数名称:索引

以下是导致错误的行/代码,位于
ValidatePlace
cmbPlace\u Validating

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

正如我在评论中所述,当未选择任何项时,
SelectedIndex
属性返回-1,这对于按索引访问数组元素是无效的索引(使用
cmbPlace.Items[m]
)。也就是说,在访问所选元素之前需要检查:

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

看起来您正在分配或试图从具有负值的数组中获取值。这是不可能的。数组将始终从0开始。
SelectedIndex
在未选择任何内容时为-1。如果(cmbPlace.SelectedIndex>=0)@user3185569,您需要始终使用
检查这一点。哇,这很有效,非常感谢@塞尔修斯·比茨:好消息。。答案贴出来了。