C# winform项目中ListView控件使用CheckBoxes属性实现单选功能

C# winform项目中ListView控件使用CheckBoxes属性实现单选功能

在做项目时需要使用ListView控件的CheckBoxes属性显示,还要在点击行时自动选中CheckBoxes和点击选中CheckBoxes时自动显示正行选中状态的单选功能。

效果图:

主要利用两个事件:listView1_ItemCheck和listView1_SelectedIndexChanged事件。

上代码:

 

[csharp] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
  1. private void listView1_ItemCheck(object sender, ItemCheckEventArgs e)  
  2. {  
  3.     if (!listView1.Items[e.Index].Checked)//如果点击的CheckBoxes没有选中  
  4.     {  
  5.         foreach (ListViewItem lv in listView1.Items)  
  6.         {  
  7.             if (lv.Checked)//取消所有已选中的CheckBoxes  
  8.             {  
  9.                 lv.Checked = false;  
  10.                 lv.Selected = false;  
  11.                // lv.BackColor = Color.White;  
  12.             }                      
  13.         }  
  14.         listView1.Items[e.Index].Selected = true;  
  15.         // lv.Checked = false;  
  16.     }  
  17.       
  18.     //int count = listView1.Items.Count;  
  19.     //ListViewItem item = listView1.Items[e.Index];  
  20.     //if (item.Checked)  
  21.     //{  
  22.     //    for (int i = 0; i < count; i++)  
  23.     //    {  
  24.     //        if (i != e.Index)  
  25.     //        {  
  26.     //            ListViewItem item1 = listView1.Items[i];  
  27.     //            item1.Checked = false;  
  28.     //        }  
  29.     //    }  
  30.     //}  
  31. }  

 

[csharp] view plain copy
 
 print?在CODE上查看代码片派生到我的代码片
    1. private void listView1_SelectedIndexChanged(object sender, EventArgs e)  
    2. {  
    3.   
    4.     foreach (ListViewItem lv in listView1.Items)  
    5.     {  
    6.   
    7.         if (lv.Selected)  
    8.         {  
    9.             //if (lv.Checked)  
    10.             //{  
    11.             //    //lv.Checked = false;  
    12.             //}  
    13.             //else  
    14.             //{  
    15.                 lv.Checked = true;  
    16.             //}  
    17.         }  
    18.         else   
    19.         {  
    20.             if (listView1.SelectedIndices.Count>0)  
    21.             {  
    22.                 if (lv.Checked)  
    23.                 {  
    24.                     lv.Checked = false;                             
    25.                 }  
    26.             }  
    27.               
    28.         }  
    29.     }  
    30.   
    31. }  
posted @ 2016-02-21 12:05  黑暗时代地表人  阅读(980)  评论(0编辑  收藏  举报