2

我对此很陌生,所以请帮忙。我有以下图片点击代码。但是,如果用户不单击图像,则会发生错误。如果用户没有单击图像并尝试继续,我如何进行错误检查以捕捉到,将显示一个消息框,通知他单击图像。

错误消息:错误位于“ListViewItem selectedItem = listView1.SelectedItems[0] 错误消息:无效参数 = '0' 的值对'索引无效

下面是我的代码:

private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    int i = e.ProgressPercentage;
    object fbUserObject = e.UserState;
    if (fbUserObject is DataRow)
    {
        var fbUser = fbUserObject as DataRow;
        var item = new ListViewItem(fbUser["friend_name"].ToString());
        item.Tag = fbUser["friend_id"];
        item.ImageIndex = i;
        listView1.Items.Add(item);
    }
    else if (fbUserObject is Image)
    {
        imageList.Images.Add(fbUserObject as Image);
    }  
}

private void imageClicked(Object sender, System.EventArgs e)
{
    ListViewItem selectedItem = listView1.SelectedItems[0];
    selectedFBId = selectedItem.Tag as string;
    selectedFBName = selectedItem.Text;

    DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
    if (dialogA == DialogResult.Yes)
    {
        TargetEmployee.Text = "Selected Target: " + selectedFBName;
        pf.Show();
        ThreadPool.QueueUserWorkItem(LoadUserDetails);
    }
}
4

3 回答 3

4

您不应该捕获异常,您应该在没有任何选定项目时处理

if(listView1.SelectedItems.Count == 0)
{
 MessageBox.Show(this, "No image");
return;
}

当您不希望发生某些事情时应该捕获异常,如果您意识到可能的问题,您应该在它成为问题之前处理它

于 2013-07-22T12:54:01.023 回答
3

像这样更改您的代码

 private void imageClicked(Object sender, System.EventArgs e)
    {
        if(listView1.SelectedItems.Count < 1)
                return;
        ListViewItem selectedItem = listView1.SelectedItems[0];
        selectedFBId = selectedItem.Tag as string;
        selectedFBName = selectedItem.Text;

        DialogResult dialogA = MessageBox.Show("Analyse employee data?", "SOC", MessageBoxButtons.YesNo);
        if (dialogA == DialogResult.Yes)
        {
            TargetEmployee.Text = "Selected Target: " + selectedFBName;
            pf.Show();
            ThreadPool.QueueUserWorkItem(LoadUserDetails);
        }
    }
于 2013-07-22T12:26:17.103 回答
1

您可以使用try { } catch { }语句进行错误处理。

一旦找到生成异常的代码行,就可以将其包装成这样的块

try
{
   int a = int.Parse("pedantic"); // This throws an error because you cannot convert
}
catch (Exception e)
{
   // Handle your error here instead of crashing your program
}
于 2013-07-22T12:21:55.947 回答