检查List <list <string>&gt;的索引不为空</list <string>

时间:2014-07-28 15:00:04

标签: c# winforms list

我有一个List<List<string>>,一个ComboBox有10个项目,当所选索引发生变化时,我使用comboBox_selectedIndexChanged事件将此索引的数据绑定到{{ 1}}。

我还有ListBoxAdd按钮,可以将数据插入我的Remove

如果前四个仍然为空,如何阻止用户从List<List<string>中选择索引5并为其添加数据?例如。告诉他,他必须先将数据放入索引1,2,3和4中。

ComboBox按钮的点击事件如下所示:

Add

我知道我可以在int selectedIndex = comboBox1.SelectedIndex; //This throws an exception when the selected index is zero, //of course it makes sense because we can't check if index 0-1 in myList is null if (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null) { myList[selectedIndex].Add(textEdit1.Text); } else MessageBox.Show("Please fill the previous indexes first."); 的{​​{1}}事件中执行此操作,但我更喜欢在此处执行此操作。

1 个答案:

答案 0 :(得分:0)

怎么样:

int selectedIndex = comboBox1.SelectedIndex;
if (selectedIndex == 1 || (myList.Count >= selectedIndex && myList[selectedIndex - 1] != null))
{
    myList[selectedIndex].Add(textEdit1.Text);
}
else
    MessageBox.Show("Please fill the previous indexes first.");

如果selectedIndex == 1为true,那么它将不会测试if语句中的第二个参数,并且不会抛出错误。如果它不是1,它将测试第二个参数,并且不会抛出您的错误。

相关问题