listView1.Items.Clear(); for (int i = 0; i < 50; i++) { ListViewItem lv = new ListViewItem(); lv.Text = "new " + i; lv.SubItems.Add("feeder " + i); listView1.Items.Add(lv); }
2.获取选择项的事件
private void listView1_SelectedIndexChanged(object sender, EventArgs e) { if (listView1.SelectedIndices != null && listView1.SelectedIndices.Count > 0) { ListView.SelectedIndexCollection c = listView1.SelectedIndices; clickname = listView1.Items[c[0]].SubItems[1].Text; } }
3.移除某行
string clickname; private void button1_Click_1(object sender, EventArgs e) { if (clickname != "") { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].SubItems[1].Text == clickname) { //ncAndIp.Remove(clickname); listView1.Items[i].Remove(); clickname = ""; break; } } } }
4.遍历并查找某项是否存在, 若存在高亮选择
private void button3_Click_1(object sender, EventArgs e) { string txt = textBox3.Text.Trim(); if (txt != "") { for (int i = 0; i < listView1.Items.Count; i++) { if (listView1.Items[i].SubItems[1].Text == txt || listView1.Items[i].SubItems[0].Text == txt) { //获得焦点, 方便选择效果 listView1.Focus(); //选择该行 listView1.Items[i].Selected = true; //滚动条滚到选择行 listView1.EnsureVisible(i); //在失去焦点的时候依然有选择效果 //listView1.HideSelection = false; break; } } } }
,