尝试查看列表框中是否选择了某个项目时引发异常

时间:2010-10-12 12:22:43

标签: c# winforms listbox

如果用户点击删除按钮但未选择列表框中的项目,我会尝试引发异常。

这就是我所拥有的:

try
{
    if (dataListBox.SelectedIndex == null)
        throw new Exception;

    //deletes selected items
    dataListBox.Items.RemoveAt(dataListBox.SelectedIndex);
    isDirty = true;
}
catch (Exception err)
{
    //spits out the errors if there are any
    MessageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

4 个答案:

答案 0 :(得分:2)

您不需要在此处抛出异常,您可以执行以下操作:

if (dataListBox.SelectedIndex == -1)
{
    MessageBox.Show(err.Message, "Enter something into the txtbox", MessageBoxButtons.OK, MessageBoxIcon.Error)
}
else
{
    //deletes selected items
    dataListBox.Items.RemoveAt(dataListBox.SelectedIndex);
    isDirty = true;
}

答案 1 :(得分:2)

使用

SelectedIndex == -1

知道没有选择任何东西。

答案 2 :(得分:2)

您不应该使用例外来检查值。

做类似的事情:

if (dataListBox.SelectedIndex >= 0)
{
  //standard flow code
}
else
{
  MessageBox.Show("Enter something into the txtbox",_
MessageBoxButtons.OK, MessageBoxIcon.Error); 
} 

代替。

答案 3 :(得分:1)

测试错误,检查-1。它缺少括号,抛出新的异常()。

然而,这在许多不同方面都是非常不合适的代码。首先是抛出Exception而不是特定的异常派生类对象。您的catch子句将捕获每个异常,包括由代码中的错误等其他错误引发的异常。您告诉用户在实际操作时输入内容。

此外,例外用于特殊情况。用户忘记做某事并没有什么特别之处。只需在if()语句中显示消息,在else子句中执行其余操作。

此外,您甚至不应允许用户陷入此陷阱。当您看到她已选中某些内容时,仅将“删除”按钮的“已启用”属性设置为“真”。

相关问题