Listbox won't display value

2019-03-04 01:24发布

问题:

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?

回答1:

Try to change this:

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

To this:

PersonList.DisplayMember = "DisplayName";