Listview C # error

I have a ListView. I want to select the first element from it and then call the method. The fact is that although I have an item in the list, I don’t know why the following code does not work when I want to select an item. help is needed. THX

listview.Items[0].Selected = true;
listview.Select();
int c =listview.SelectedItems.Count;
MessageBox.Show(c + ": and : " + listview.Items[0].ToString()); .//here the c=0 and it should be 1:(
//  Thread.Sleep(3000);
method();  

I have:

ListViewItem it = new ListViewItem("a");
it.SubItems.Add("s");
it.SubItems.Add(""v");
it.Tag = call;
listview.Items.Add(it);
+3
source share
3 answers

for

System.Windows.Forms.ListViewItem listViewItem4 = new System.Windows.Forms.ListViewItem("fdasf");
System.Windows.Forms.ListViewItem listViewItem5 = new System.Windows.Forms.ListViewItem("sdfsadf");
System.Windows.Forms.ListViewItem listViewItem6 = new System.Windows.Forms.ListViewItem("gdsgdfg");

and

this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
    listViewItem4,
    listViewItem5,
    listViewItem6});
this.listView1.Location = new System.Drawing.Point(84, 88);
this.listView1.Name = "listView1";
this.listView1.Size = new System.Drawing.Size(121, 97);
this.listView1.TabIndex = 0;
this.listView1.UseCompatibleStateImageBehavior = false;
this.listView1.View = System.Windows.Forms.View.List;

it works, and c - 1

listView1.Items[0].Selected = true;
listView1.Select();
int c =listView1.SelectedItems.Count;
MessageBox.Show(c + ": and : " + listView1.Items[0].ToString());
//  Thread.Sleep(3000);
method();  

enter image description here

The problem is probably elsewhere.

+1
source

It seems you are using the correct way to select an element:

listview.Items[0].Selected = true;
+1
source

listview.SelectedIndex = 1; try it.

0
source

All Articles