Pregunta

From my usercontrol I tried to show value inside a listbox named PersonList

Usercontrol Code:

BindingList<NotifiablePerson> PerSonList = new BindingList<NotifiablePerson>();

SqlCommand prsonListCmd = new SqlCommand("SQL QUERY", conn);
SqlDataReader dr = prsonListCmd.ExecuteReader();
 if (dr.HasRows)
   {
      while (dr.Read())
        {
           //collect value from database and save inside Fname and Lname variable

           NotifiablePerson np = PerSonList.AddNew();
           np.FirstName = Fname;
           np.LastName = Lname; 
        }               
  }
PersonList.DisplayMember = "np.FirstName" + "np.LastName";
PersonList.ValueMember = "np.FirstName";
PersonList.DataSource = PerSonList;

NotifiablePerson class code:

namespace SMS
{
 class NotifiablePerson : MyComponentModel.NotifyProperyChangedBase
  {
    private string _firstName;
    public string FirstName
        {
         get { return _firstName; }
         set{
             if (this.CheckPropertyChanged<string>("FirstName", ref _firstName, ref value))
             {
               this.DisplayNameChanged();
             }
            }
        }

    private string _lastName;
    public string LastName
        {
        get { return _lastName; }
        set{
           if (this.CheckPropertyChanged<string>("LastName", ref _lastName, ref value))
             {
              this.DisplayNameChanged();
             }
           }
        }

        public string DisplayName
        {
            get { return _firstName + " " + _lastName; }
        }

        private void DisplayNameChanged()
        {
            this.FirePropertyChanged("DisplayName");
        }
    }
}

But listbox only display a list of SMS.NotifiablePerson , not the actual value I specified. Here I set valuemember. And it works correctly and display related values in sidebox. But only listbox doesn't display correct value.

What is wrong with this code?

¿Fue útil?

Solución

Try to change this:

PersonList.DisplayMember = "np.FirstName" + "np.LastName";

To this:

PersonList.DisplayMember = "DisplayName";
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top