Link to home
Create AccountLog in
Avatar of davecove
davecoveFlag for United States of America

asked on

I'm doing ListView Wrong

I have winforms ListView to which I have added items that have subitems. Looks good. I have enabled CheckBoxes. I have a ListView.Click handler enabled. When I click on a row, nothing happens... surprising, but OK.

When I click on a checkbox in a row, the ListView.Click() handler fires but thows an exception on the first line:

ListViewItem item = alarmList.SelectedItems[0];

In fact, SelectedItems has count of 0. It is like the line is not selected, even tho it responded to the Click. How can this be?

How can I get the Item for the checkBox I just clicked on?

Dave
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Use another event. Try
private void button3_Click(object sender, EventArgs e)
        {
            ListViewItem i1 = new ListViewItem("hello");
            ListViewItem.ListViewSubItem lvsi1 = new ListViewItem.ListViewSubItem( i1,"abc");
  
            i1.SubItems.Add(lvsi1);
            ListViewItem i2 = new ListViewItem("goodbye");
            ListViewItem.ListViewSubItem lvsi2 = new ListViewItem.ListViewSubItem(i2,"def");
            i2.SubItems.Add(lvsi2);
            this.listView1.Items.Add(i1);
            this.listView1.Items.Add(i2);
        }


        private void listView1_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            ListViewItem item = e.Item;
            MessageBox.Show(item.Text);
        }

Open in new window

Avatar of davecove

ASKER

I tried ItemChecked, but that also fires off when an item is added to the list. Apparently being instantiated counts as a checked event.

 I am doing a lot of add/delete in this list and I don't want to get triggered on the .Add()s.... only when the user actually does something.  That's why the .Click()

Dave
ASKER CERTIFIED SOLUTION
Avatar of Dmitry G
Dmitry G
Flag of New Zealand image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account