0

I want to set the values of my selected item in my combo box to a variable(person) so that I can compare a person value to a value in my sqlite database. Here is my code:

private void cboSelectClient_SelectedIndexChanged(object sender, EventArgs e)
{
    string str;
    personSearch = new Person();
    selectedPersonList = new List<Person>();

My problem is in the next line, where it should set my person variable items equal too the items that is in the combobox.

    personSearch = cboSelectClient.SelectedItem as Person;

   _pBl.PopulateSelectedPersonList(personSearch, ref selectedPersonList);  

   foreach (Person person in selectedPersonList)
   {
       txtAge.Text = Convert.ToString(person.Age);
       txtEmail.Text = person.Email;
       txtFirstName.Text = person.FirstName;
       txtID.Text = Convert.ToString(person.ID);
       txtLastName.Text = person.LastName;

       lstItemsAdded.Items.Add(person.Item);
   }      
}

This is how i populate my combobox:

foreach (Person PersonItem in _listAllData)
{
     if (PersonItem.FirstName != equalPerson.FirstName) //Add name en add  nie die name wat klaar in is nie... VIND UIT HOE OM NET N SEKERE DEEL TE ADD..
     {
         cboSelectClient.Items.Add(PersonItem.ID +" : "
            + PersonItem.FirstName + " " 
            + PersonItem.LastName + " " 
            + PersonItem.Age + " " 
            + PersonItem.Email + " " 
            + PersonItem.Item.ItemCode 
            + " " + PersonItem.Item.ItemDescription 
            + " " + PersonItem.Item.ItemName + " " 
            + PersonItem.Item.ItemPrice);

      }

      equalPerson = PersonItem;
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user2980509
  • 132
  • 1
  • 3
  • 12

1 Answers1

1

Problem here is that you are populating your ComboBox with string, not with actual Person object. Of course this string cannot be converted directly back to object, therefore your conversion fails and personSearch is assigned to null.

To resolve the issue you need to:

  1. Populate ComboBox with actual Person objects. Make sure ComboBox.ValueMemeber is null.
  2. In Person class define some property like Text and set DisplayMember to it or override ToString to control how entries in CombobBox appear on the UI
Andrei
  • 55,890
  • 9
  • 87
  • 108