我有一个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();
}
}
问题是当我尝试测试验证errormessage1和cmbPlace.Focus()时输入'null'或'not in index'文本,它们不会触发并显示错误
InvalidArgument ='-1'的值对'index'无效。参数名称:index
这是导致错误的行/代码,位于ValidatePlace
和cmbPlace_Validating
if ((cmbPlace.Items[m]).ToString() == cmbPlace.Text)
答案 0 :(得分:2)
正如我在评论中发布的那样,当没有选择项时,SelectedIndex
属性返回-1,这是通过索引访问数组元素的无效索引(使用cmbPlace.Items[m]
)。这样说,您需要在访问所选元素之前进行检查:
if(cmbPlace.SelectedIndex >= 0)
{
// do something
}
else
{
// No item selected, handle that or return
}