listView.Selectedindeces [0]未处理的异常

时间:2019-03-01 00:27:26

标签: c#

我试图在ListView框中找到用户选择的列表项,但是,每当我尝试使用listview.SelectedIndeces [0]时,都会收到未处理的异常错误,指出“ InvalidArgument =值'0'不适用于“索引””。

代码如下:

x1, y1, x2, y2 = rect = win32gui.GetWindowRect(WIN)
res = (x2 - x1, y2-y1)
item_pos = (x2-254, y2-372)
del_pos = (x2-302, y2-263)
tree_pos = (x2-467, y2-291)


click(item_pos, mouse.Button.right)
sleep(.4)
click(del_pos, mouse.Button.left)
sleep(.4)
k.press(keyboard.Key.enter)
k.release(keyboard.Key.enter)
sleep(2)
click(tree_pos, mouse.Button.left)

答案:

    private void TabPage3_Click(object sender, EventArgs e)
    {
        foreach (Child child in Children)
        {
            editChildListView.Items.Add(new ListViewItem(new string[] {child.name, child.dob.ToString("dd/MM/yy"), child.comment }));
        }
        if (editChildListView.Items.Count >= 0)
        {
            int selectedIndex = editChildListView.SelectedIndices[0];
            editNameBox.Text = Children[selectedIndex].name;
        }
    }

需要从listview_SelectedIndexChanged函数而不是tab3_Click函数中调用该方法

1 个答案:

答案 0 :(得分:0)

如果愿意

 int selectedIndex = editChildListView.SelectedIndices.FirstOrDefault();

然后,如果未选择任何内容,您将不会收到错误消息。

您可能只想检查是否已选中某项。