Click here to Skip to main content
Click here to Skip to main content

How to set values into ComboBox Items

, 26 Jun 2002
Rate this:
Please Sign up or sign in to vote.
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 Smile | :)

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
AuthorID AuthorName
1 Tomohiro
2 Henry
3 Ben
4 Jungwon
tblBooks
BookID AuthorID Title
1 1 Hello World
2 1 Japanese Culture
3 1 Fujisan
4 2 Spider
5 2 CDR
6 2 Beginning VB6
7 3 Smart Business
8 3 MBA holder
9 3 Web Business
10 4 English 666
11 4 Korean 102
12 4 How to be beautiful like me
13 4 Precalculous for even stupids
14 4 Super 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
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
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.

    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
        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! Blush | :O )

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

Share

About the Author

Tomohiro

Japan Japan
I just started C#.

Comments and Discussions

 
QuestionSame process required in VB and with datatable filled by dataadapter instead of reader Pinmemberatul vb28-Jan-14 4:48 
AnswerRe: Same process required in VB and with datatable filled by dataadapter instead of reader Pinmemberatul vb28-Jan-14 6:23 
QuestionHow to add items to our combobox very easy in .Net (C#) WinForms Pinmemberberkut200619-Jun-13 15:46 
QuestionHay! i have the same problem and looking for solution in VB.NET Can you help me ? Pinmemberlaxi30028-Sep-11 14:39 
GeneralExcellent PinmemberRubenCervantes6-Jun-11 4:27 
GeneralAnonymous types PinmemberMember 791061325-May-11 4:52 
Generalajish Pinmemberajish10126-Jul-07 2:13 
Generalinsert item Pinmemberbalanjingot9-May-07 23:26 
GeneralThank you very much Pinmembertamir_ku8-Apr-07 6:57 
GeneralThanks PinmemberSveinErik9-Mar-07 7:52 
QuestionHow To Search The Item From ComboBox Pinmember..HuNTeR..25-Feb-07 4:58 
AnswerRe: How To Search The Item From ComboBox Pinmember..HuNTeR..1-Mar-07 10:19 
GeneralAn alternative method to adding items to a ComboBox Pinmemberjonmidd20-Feb-07 23:50 
QuestionHow to Get the Value form ComboBox Pinmember..HuNTeR..16-Dec-06 6:32 
GeneralEasier way to do the same Pinmemberyudfgdgjkdgh1-Sep-06 0:00 
QuestionAddValue PinmemberNoferura18-Aug-06 1:28 
AnswerRe: AddValue Pinmemberdatacore28-Mar-07 3:18 
GeneralGenerics PinmemberBjornar16-Apr-06 16:03 
GeneralExcellent work PinsussDamien Pitman4-Jul-05 16:51 
Generalother tip... Pinmembermainroot12-May-05 20:14 
GeneralValueMember PinmemberSignMan3599-Feb-05 16:47 
AnswerRe: ValueMember Pinmembermschrijvers14-Aug-07 1:55 
GeneralNeed info....Item Selection PinmemberMd Saleem Navalur4-Feb-05 6:49 
GeneralSelectedItem Pinsussagir19-Jul-04 6:17 
GeneralThanks Pinmemberwal3360426-Feb-04 20:16 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 27 Jun 2002
Article Copyright 2002 by Tomohiro
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid