我想使用 Windows 窗体作为注册表单;同时我决定将 ComboBox 项目导入到数组中。当我按下 Save 按钮时,我可以使用 Next 和 Previous 按钮在人员表单之间切换。所以这是我的代码:
private void btnNext_Click(object sender, EventArgs e)
{
if (items != null && index < size - 1)
{
index++;
comboBox1.Items.Clear();
comboBox1.Items.Add(items[index]);
comboBox1.SelectedItem = 0;
}
}
现在调试器向我显示错误,表明参数“item”不能为空。
我希望我可以允许用户将数据导入列表框,并通过按 Next 和 Previous 按钮在人员信息之间切换,然后选择组合框的项目。
您的代码的问题在于您没有检查索引是否超出数组中最后一项的索引是否超出范围。在将新项目添加到组合框之前,请检查索引是否大于数组中最后一项的索引并重置为 0。
if(items != null){
// Make sure index is within bounds
if(index < size){
comboBox1.Items.Clear();
comboBox1.Items.Add(items[index]);
comboBox1.SelectedItem = 0;
index += 1;
}
}
您不需要做
index < size -1
。这就是导致您的程序出现错误的原因。