C# WindowsForm 组合框

问题描述 投票:0回答:1

我想使用windows表单作为注册表单;同时,我决定在按下“保存”按钮时将 ComboBox 项目导入到数组中,然后我可以使用下一个和上一个按钮在人员表单之间切换。所以这是我的代码

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”不能为空。

我希望我可以允许用户将数据导入列表框,并通过按下一个和上一个按钮并选择组合框的项目来在人员信息之间切换。

c# winforms combobox
1个回答
0
投票

您的代码的问题是您没有检查索引是否超出数组中最后一项的索引。在向组合框添加新项目之前,请检查索引是否大于数组中最后一项的索引并重置为 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
,这就是导致程序错误的原因

© www.soinside.com 2019 - 2024. All rights reserved.