Click here to Skip to main content
15,883,901 members
Articles / Programming Languages / C#
Article

How to set values into ComboBox Items

Rate me:
Please Sign up or sign in to vote.
4.56/5 (31 votes)
26 Jun 20023 min read 709.1K   5.6K   57   35
How to use ValueMember with ADO.NET.

Sample Image - ValueMemberSample.gif

Introduction

I am a beginner in C# for 2 months. And recently, I had a hard time to find out how to set values into ComboBox items. I was looking for the answer from books, sample code in Internet and MSDN. We can make it display Primary ID instead of some meaningful names, and that was not what I wanted. I do not want to see meaningless ID anymore in my life! The hint to find it out is in the MSDN. You can find a code in the ValueMember section. But the code is 80%. Something is missing... I tried to find it out, but I could not get it for a week. And finally when I tried to create a class accidentally, a miracle happened! Anyway I hope I can help people not to suffer like I did.

Create a sample software

We are going to create a sample software (see the picture) which has a ComboBox for author's name list and when you select an author name, it is displaying book titles into a ListBox. Key point is, of course, that I did not display Author ID but Author name. In addition, I use ADO.NET to store the data, so we can study it, too :-)

Prepare database

I use MS Access to store the data. And tblBooks has foreign key (AuthorID) to make a relationship with AuthorID in the tblAuthors.

books.mdb (location => /bin/debug/books.mdb)
tblAuthors
AuthorIDAuthorName
1Tomohiro
2Henry
3Ben
4Jungwon
tblBooks
BookIDAuthorIDTitle
11Hello World
21Japanese Culture
31Fujisan
42Spider
52CDR
62Beginning VB6
73Smart Business
83MBA holder
93Web Business
104English 666
114Korean 102
124How to be beautiful like me
134Precalculous for even stupids
144Super duper cooking

Create interface

Now it is time to start! You need to make sure you have a ComboBox (cboAutors) and ListBox (lstBooks). And certainly, you can change interface to whatever you like, but again, remember, you have to have the two controls.

  • ComboBox - cboAutors
  • ListBox - lstBooks

Create module level values

Well, we need to create two module level values first. And then you give a type and a path for database to the connection value. And also you need to make sure to add Using System.Data.OleDb on the top.

Values entry:

  • private bool AuthorsHaveBeenAdded - Make sure your cboAuthors ComboBox built.
  • private OleDbConnection conn - Connection to the Books.mdb
C#
private OleDbConnection conn;
private bool AuthorsHaveBeenAdded=false;
public Form1()
    {
        InitializeComponent();
        // Create Connection.
        this.conn = new OleDbConnection("
        PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Books.mdb;");

Bulid cboAutors ComboBox

Now we will set an AuthorID for valueMember, and an Author Name for DisplayMember. The order is to read data from database, to pass the data into ArrayList and to pass to cboAuthors ComboBox. And we will create an AddValue function later.

Values entry:

  • OleDbCommand cmd - Create SQL command
  • OleDbDataReader rsAutors - Read tblAuthors table
  • ArrayList Authors - Store Authors table data
C#
private void buildcboAuthors()
{
    OleDbCommand cmd = new OleDbCommand("SELECT * FROM tblAuthors",conn);
    this.conn .Open ();
    OleDbDataReader rsAutors = cmd.ExecuteReader();
    ArrayList Authors = new ArrayList();

    while(rsAutors.Read())
    {
        Authors.Add (new AddValue
            (rsAutors.GetString(1),rsAutors.GetInt32 (0)));
                
    }
    rsAutors.Close();
    this.conn.Close();
            
    this.cboAuthors.DataSource = Authors;
    this.cboAuthors .DisplayMember ="Display";
    this.cboAuthors.ValueMember = "Value";        
    AuthorsHaveBeenAdded=true;                        
}

Then call buildcboAuthors().

    InitializeComponent();
    // Create Connection.
    this.conn = new OleDbConnection(
       "PROVIDER=Microsoft.Jet.OLEDB.4.0;Data Source=Books.mdb;");
            
    buildcboAuthors();
}

Create AddValue Class

This is the one I spent a week. This is simple, just getting values and creating properties.

C#
public class AddValue
{
    private string m_Display;
    private long m_Value;
    public AddValue(string Display, long Value)
    {
        m_Display = Display;
        m_Value = Value;
    }
    public string Display
    {
        get{return m_Display;}
    }
    public long Value
    {
        get{return m_Value;}
    }
}

Build lstBooks ListBox

Now we will display book titles. We can use WHERE to display what we want. And call buidlstBooks in the cboAuthors_SelectedIndexChanged event.

Values entry:

  • OleDbCommand cmd- Create SQL command
  • OleDbDataReader rsBooks - Read tblBooks table
C#
private void buildlstBooks()
{
    this.lstBooks.Items.Clear();
    OleDbCommand cmd = new OleDbCommand(
        "SELECT * FROM tblBooks WHERE AuthorID =" +
        this.cboAuthors.SelectedValue,conn);
    this.conn .Open ();
    OleDbDataReader rsBooks = cmd.ExecuteReader();
    while(rsBooks.Read ())
    {
        this.lstBooks .Items.Add (rsBooks.GetString (2));
    }
    rsBooks.Close ();
    this.conn.Close ();

}

private void cboAuthors_SelectedIndexChanged
            (object sender, System.EventArgs e)
{
    if(this.AuthorsHaveBeenAdded)
        buildlstBooks();
}

Conclution

I guess that's it. Happy programming! :0)

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Japan Japan
I just started C#.

Comments and Discussions

 
QuestionSame process required in VB and with datatable filled by dataadapter instead of reader Pin
atul sharma 512628-Jan-14 3:48
atul sharma 512628-Jan-14 3:48 
AnswerRe: Same process required in VB and with datatable filled by dataadapter instead of reader Pin
atul sharma 512628-Jan-14 5:23
atul sharma 512628-Jan-14 5:23 
QuestionHay! i have the same problem and looking for solution in VB.NET Can you help me ? Pin
laxi30028-Sep-11 13:39
laxi30028-Sep-11 13:39 
GeneralExcellent Pin
RubenCervantes6-Jun-11 3:27
RubenCervantes6-Jun-11 3:27 
GeneralAnonymous types Pin
Sumbas8025-May-11 3:52
Sumbas8025-May-11 3:52 
Generalajish Pin
ajish10126-Jul-07 1:13
ajish10126-Jul-07 1:13 
Generalinsert item Pin
balanjingot9-May-07 22:26
balanjingot9-May-07 22:26 
GeneralThank you very much Pin
tamir_ku8-Apr-07 5:57
tamir_ku8-Apr-07 5:57 
GeneralThanks Pin
SveinErik9-Mar-07 6:52
SveinErik9-Mar-07 6:52 
QuestionHow To Search The Item From ComboBox Pin
Sonal Satpute25-Feb-07 3:58
Sonal Satpute25-Feb-07 3:58 
AnswerRe: How To Search The Item From ComboBox Pin
Sonal Satpute1-Mar-07 9:19
Sonal Satpute1-Mar-07 9:19 
GeneralAn alternative method to adding items to a ComboBox Pin
VolcanicZone20-Feb-07 22:50
VolcanicZone20-Feb-07 22:50 
QuestionHow to Get the Value form ComboBox Pin
Sonal Satpute16-Dec-06 5:32
Sonal Satpute16-Dec-06 5:32 
GeneralEasier way to do the same Pin
yudfgdgjkdgh31-Aug-06 23:00
yudfgdgjkdgh31-Aug-06 23:00 
QuestionAddValue Pin
Noferura18-Aug-06 0:28
Noferura18-Aug-06 0:28 
AnswerRe: AddValue Pin
datacore28-Mar-07 2:18
datacore28-Mar-07 2:18 
GeneralGenerics Pin
Bjornar16-Apr-06 15:03
Bjornar16-Apr-06 15:03 
GeneralExcellent work Pin
Damien Pitman4-Jul-05 15:51
sussDamien Pitman4-Jul-05 15:51 
Generalother tip... Pin
mainroot12-May-05 19:14
mainroot12-May-05 19:14 
GeneralValueMember Pin
SignMan3599-Feb-05 15:47
SignMan3599-Feb-05 15:47 
AnswerRe: ValueMember Pin
mschrijvers14-Aug-07 0:55
mschrijvers14-Aug-07 0:55 
GeneralNeed info....Item Selection Pin
Md Saleem Navalur4-Feb-05 5:49
Md Saleem Navalur4-Feb-05 5:49 
GeneralSelectedItem Pin
aglt19-Jul-04 5:17
aglt19-Jul-04 5:17 
GeneralThanks Pin
wal3360426-Feb-04 19:16
wal3360426-Feb-04 19:16 
GeneralNo datasource Pin
haezeban27-May-03 0:47
haezeban27-May-03 0:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.