ListView 选择多项目返回的之前的那项
当ListView多选时返回第一次选中的项索引
正确
定义一个变量
=-1 表示第一次没选任何一项
private int FirstSelectedIndex =-1; |
更新FirstSelectedIndex 的值一定要放在Mouse_Click
放在 listView1_SelectedIndexChanged或listView1_ItemSelectionChanged无效
private void listView1_MouseClick(object sender, MouseEventArgs e)
{
int count = listView1.SelectedItems.Count;
if (count > 0)
{
int Index = listView1.SelectedItems[0].Index;
if (count == 1)
FirstSelectedIndex = Index;
}
} |
高亮选中第一次选择的项
Form1_Click
private void Form1_Click(object sender, EventArgs e)
{
if (listView1.Items.Count > 0)
{
if (FirstSelectedIndex != -1)
{
//RUN
listView1.MultiSelect = false;
listView1.Focus();
Text = listView1.Items[FirstSelectedIndex].Text;
listView1.Items[FirstSelectedIndex].Selected = true;
listView1.MultiSelect = true;
}
if ((FirstSelectedIndex == -1) && (listView1.SelectedItems.Count > 0))
{
//RUN
FirstSelectedIndex = 0;
listView1.MultiSelect = false;
listView1.Focus();
Text = listView1.Items[FirstSelectedIndex].Text;
listView1.Items[FirstSelectedIndex].Selected = true;
listView1.MultiSelect = true;
}
}
} |