列表框不会显示值

时间:2013-12-23 10:10:31

标签: c# winforms listbox inotifypropertychanged

从我的usercontrol中,我试图在名为PersonList的列表框中显示值

用户控制代码:

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类代码:

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");
        }
    }
}

但是列表框只显示 SMS.NotifiablePerson 的列表,而不是我指定的实际值。我在这里设置了valuemember。并且它可以正常工作并在sidebox中显示相关值。但只有列表框不显示正确的值。

此代码有什么问题?

1 个答案:

答案 0 :(得分:0)

尝试改变这一点:

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

对此:

PersonList.DisplayMember = "DisplayName";