对此我很陌生,所以请帮忙。 我有以下图片点击代码。 但是,如果用户未单击图像,则会发生错误。 如何进行错误检查以确定如果用户未单击图像并尝试继续,则会显示一个消息框,通知他单击图像。
错误消息:错误位于“ListViewItem selectedItem = listView1.SelectedItems [0]错误消息:无效参数=值'0'对'index
无效以下是我的代码:
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);
}
}
答案 0 :(得分:4)
您不应该捕获异常,您应该在没有任何选定项目时进行处理
if(listView1.SelectedItems.Count == 0)
{
MessageBox.Show(this, "No image");
return;
}
当您不希望发生某些事情时应该抓住例外情况,如果您知道可能存在的问题,您应该在问题出现之前处理
答案 1 :(得分: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);
}
}
答案 2 :(得分: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
}