none
List view team Exist

    Question

  • validation

                    

    if (Formname == "Add Device Property")
                {
                    string text = lstGroup.SelectedItems[0].Text;

                    if (lstSelectedGroup.Items.Count == 0)
                    {
                        lstSelectedGroup.Items.Add(lstGroup.SelectedItems[0].Text);
                        LV.SubItems.Add(lstGroup.SelectedItems[0].Text);
                    }
                    else if (lstSelectedGroup.FindItemWithText(text))
                    {
                        MessageBox.Show("Allredy Exist");
                    }
                    else
                    {
                        lstSelectedGroup.Items.Add(lstGroup.SelectedItems[0].Text);
                    }
                }

    want to solution for that if record exist


    Pramod

    • Changed type Pramod Lawate Monday, April 09, 2012 9:56 AM
    • Moved by CoolDadTxMVP Monday, April 09, 2012 3:26 PM Winforms related (From:Visual C# General)
    Monday, April 09, 2012 9:54 AM

Answers

  • LisView is quite complicated (actually very different) controls then all others. 

    So this is how you should do it to salve the problem with diplicates (or items existance):

            bool bFlag; //class variable!
            private void listView1_SelectedIndexChanged(object sender, EventArgs e)
            {
                if (!bFlag)
                {
                    bFlag = true;
                    //adding items to listView2:
                    bool bExists = false;
                    ListViewItem lvi = listView1.SelectedItems[0];
                    foreach (ListViewItem item in listView2.Items)
                    {
                        if (item.Text.Equals(lvi.Text))
                        {
                            bExists = true;
                            break;
                        }
                    }
                    if (!bExists)
                        listView2.Items.Add(lvi.Text);
                }
                else
                    bFlag = false;
            }

    As you can see, I an using sme boolean flag, this is becuase the event SelectedIndexChanged is firing twice when clicked 2nd time and more. When you click some item for the 2nd time and more the code is still looking for the item that was clicked before, so the SelectedItem is now null (the new selected item, which is really not yet selected, but will be selected in next time round - thats why my code skips the 1st loop).


    Mitja


    Monday, April 09, 2012 10:14 AM