This blog is subject the DISCLAIMER below.

Friday, April 25, 2008

How to bind ComboBox to an array of object?

Q: How to bind ComboBox to an array of object?

A:

Assume we have class like Student class

   1: public class Student
   2:     {
   3:         int id;
   4:  
   5:         public int ID
   6:         {
   7:             get { return id; }
   8:             set { id = value; }
   9:         }
  10:         string firstName;
  11:  
  12:         public string FirstName
  13:         {
  14:             get { return firstName; }
  15:             set { firstName = value; }
  16:         }
  17:         string lastName;
  18:  
  19:         public string LastName
  20:         {
  21:             get { return lastName; }
  22:             set { lastName = value; }
  23:         }
  24:  
  25:         public string FullName
  26:         {
  27:             get { return firstName + " " + lastName; }
  28:         }
  29:  
  30:         public Student(int id, string firstName, string lastName)
  31:         {
  32:             this.id = id;
  33:             this.firstName = firstName;
  34:             this.lastName = lastName;
  35:         }
  36:     }



what we need is to bind an array of Student to ComboBox and let the ComboBox shows the student FullName and bind their IDs to be used later.



So, what we need is to use some ComboBox properties like DisplayMember and ValueMember




   1: Student[] students = new Student[3];
   2:  
   3:             students[0] = new Student(1, "Ramy", "Mahrous");
   4:             students[1] = new Student(2, "FCI", "Helwan");
   5:             students[2] = new Student(3, "X", "Y");
   6:  
   7:             comboBox1.Items.AddRange(students);
   8:             
   9:             comboBox1.DataSource = students;
  10:             comboBox1.ValueMember = "ID";
  11:             comboBox1.DisplayMember = "FullName";




And now, ComboBox shows the FullName without overriding ToString method which is not the solution if we need to bind some properties.



Untitled

No comments: