CRK
CRK

Reputation: 333

Binding a ListBox with ValueMember

I extended the ListBox to built my CustomListbox.

It will accept the classobject array as datasource and I override OnDrawItem() to display them by reading the classobject array.

Upto here everything is working fine. The problem is I am not able to read the ValueMember of the Listbox because I havent assigned it. I want to add one of the property of my classObject as Value Member

Pseudo Code:

public class myModel
{
  int id;
  string name;
  XXXXXXXXX
  XXXXXXXXX
}

myModel[] ds = getData();
//myCustomListbox.ValueMember = "id";   //this doesnt seem to work
myCustomListbox.DataSource =ds;

I repeat, the OnDrawItem() will draw the required display values. Is there any method i can override like this to add the Value Items also?

Upvotes: 0

Views: 512

Answers (2)

Rajitha
Rajitha

Reputation: 1

ListBox binding with a data table in C# (in windows applications) is necessary to add the value members.

If we make the code without value member like as follows,

 private void button1_Click(object sender, EventArgs e)
    {
        SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con);
        da.Fill(dt);

        listBox1.DataSource = dt;
        // listBox1.ValueMember = "data";  //data is one of the coloumn of the table...

    }

The output for the above code is given below

System.Data.DataRowView

System.Data.DataRowView

System.Data.DataRowView

If we provide value member in code like as follows

private void button1_Click(object sender, EventArgs e)
  {
    SqlDataAdapter da = new SqlDataAdapter("select * from Table1",con);
    da.Fill(dt);
    listBox1.DataSource = dt;
    listBox1.ValueMember = "data";  //data is one of the coloumn of the table...
  }

The output will be...

The list of the particular column in the table. here 'data' .

Upvotes: 0

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236208

Binding works with properties only. Change your field to property (and make sure it is public - by default class members are private)

public class myModel
{
   public int id { get; set; }
   public string name { get; set; }
   // ...
}

Now all should be OK:

myModel[] ds = getData();
myCustomListbox.ValueMember = "id";
myCustomListbox.DataSource = ds;

BTW C# naming guidelines suggest to use Pascal Names for properties, methods and type names.

Upvotes: 1

Related Questions