Listview控件实现已选择效果
Winform中用Listview控件实现更新点击选择后已选择效果,如图:
代码如下:
private void frmSelect_Load(object sender, EventArgs e) { //初始化listSel数据 this.listSel.View = View.SmallIcon; this.listSel.Items.Clear(); this.listSel.Groups.Clear(); ListViewGroup grpSel = new ListViewGroup(); grpSel.Name = "Select"; grpSel.Header = "已选择"; this.listSel.Groups.Add(grpSel); //初始化listChoose数据 for (int i = 1; i < 21; i++) { ListViewItem lvi = new ListViewItem("第"+i.ToString()+"项"); lvi.Group = grpSel; this.listChoose .Items.Add(lvi); } } //点击选中事件(点击某一项时,在已选项中显示) private void listChoose_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e) { if (e.IsSelected) //该事件会进入2次,前一项取消时进入,新一项点击时进入 { ListViewItem lvi = e.Item.Clone() as ListViewItem; //不能在多处添加或插入项。必须首先将其从当前位置移除或将其克隆。 if (lvi!=null ) { foreach (ListViewItem item in this.listSel.Items) { if (item.Text==e.Item.Text) //已存在的话 弹窗提示 { MessageBox.Show(e.Item.Text+"已存在"); return; } } this.listSel.Items.Add(lvi); //已选项中添加当前选中项 } } } //点击已选择项,删除当前项 private void listSel_Click(object sender, EventArgs e) { if (this.listSel.SelectedItems.Count>0) //有已选项 { this.listSel.Items.Remove(this.listSel.SelectedItems[0]); //删除已选项 } }
至于为什么更新已选项的时候为什么用Click事件,请参看 InvalidArgument=Value of '1' is not valid for 'index'