[英]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). 我有一个cmbPlace(combobox),它的项目会自动用System.IO驱动器(C:\\,D:\\等)填充。 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 问题是,当我尝试测试验证错误时,message1和cmbPlace.Focus()就像输入“空”或“不在索引中”文本一样,它们不会触发并显示错误
InvalidArgument=Value of '-1' is not valid for 'index'. InvalidArgument =值“ -1”对“索引”无效。 Parameter name: index 参数名称:索引
here's the line/code that cause error, in ValidatePlace
and cmbPlace_Validating
这是在ValidatePlace
和cmbPlace_Validating
中导致错误的行/代码
if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)
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]
). 正如我在评论中所张贴的那样,当未选择任何项目时, SelectedIndex
属性返回-1,这对于按索引访问数组元素(使用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.