0
int selectedRowIndex = 0;    
private void listViewUserList_SelectedIndexChanged(object sender, EventArgs e)
{
    if(listViewUserList.SelectedIndices.Count == 0)
       return;
}
private void Form_Load(object sender, EventArgs e)
{
    if(listViewUserList.Items.Count > 0)
    {
        listViewUserList.Items[selectedRowIndex].Selected = true;
        listViewUserList.Select();
    }
}

在表单加载时,我选择ListView. 但是当我选择空白行时,它会从ListView.

单击空白行然后选择先前选择的行时我该怎么办?我在谷歌上搜索过,但没有找到任何好的答案。stackoverflow 上的答案仅适用于 WPF,不适用于 windows 形式。

4

2 回答 2

0

这可以通过为ListView'MouseUp事件添加事件处理程序来完成。如果您仍然需要SelectedIndexChanged它的委托方法的事件处理程序,请listViewUserList_SelectedIndexChanged从中删除任何处理项目选择的代码:

private void listViewUserList_SelectedIndexChanged(object sender, EventArgs e)
{
    // remove the 2 lines below, as the selection handling is done in the
    // MouseUp event handler

    //if(listViewUserList.SelectedIndices.Count == 0)
    //   return;

    // TODO: get the column data
}

添加以下事件处理程序:

listViewUserList.MouseUp += new MouseEventHandler(this.listViewUserList_MouseUp);

和以下方法:

private void listViewUserList_MouseUp(object sender, MouseEventArgs e)
{
    if (listViewUserList.SelectedItems.Count > 0)
    {
        selectedRowIndex = listViewUserList.SelectedItems[0].Index;
    }
    else
    {
        listViewUserList.Items[selectedRowIndex].Selected = true;
    }
}
于 2013-05-14T07:41:23.620 回答
0
  1. 保存类中的前一个索引。
  2. 如果当前索引指向一个空字符串,则使用 (1) 将选择更改回之前的选择
  3. 然后调用myListView.Select()

代码:

 private void Form_Load(object sender, EventArgs e)
 {
     if(listViewUserList.Items.Count > 0 && (String.Empty != listViewUserList.Items[selectedRowIndex].ToString() ))
     {
         listViewUserList.Items[selectedRowIndex].Selected = true;
         listViewUserList.Select();
     }
 }
于 2013-05-14T06:43:06.147 回答