Click here to Skip to main content
12,243,173 members (22,161 online)
Click here to Skip to main content
Add your own
alternative version

Stats

637K views
5.3K downloads
56 bookmarked
Posted

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#.

You may also be interested in...

Comments and Discussions

 
QuestionSame process required in VB and with datatable filled by dataadapter instead of reader Pin
atul vb28-Jan-14 4:48
memberatul vb28-Jan-14 4:48 
AnswerRe: Same process required in VB and with datatable filled by dataadapter instead of reader Pin
atul vb28-Jan-14 6:23
memberatul vb28-Jan-14 6:23 
QuestionHay! i have the same problem and looking for solution in VB.NET Can you help me ? Pin
laxi30028-Sep-11 14:39
memberlaxi30028-Sep-11 14:39 
GeneralExcellent Pin
RubenCervantes6-Jun-11 4:27
memberRubenCervantes6-Jun-11 4:27 
GeneralAnonymous types Pin
Member 791061325-May-11 4:52
memberMember 791061325-May-11 4:52 
Generalajish Pin
ajish10126-Jul-07 2:13
memberajish10126-Jul-07 2:13 
Generalinsert item Pin
balanjingot9-May-07 23:26
memberbalanjingot9-May-07 23:26 
GeneralThank you very much Pin
tamir_ku8-Apr-07 6:57
membertamir_ku8-Apr-07 6:57 
GeneralThanks Pin
SveinErik9-Mar-07 7:52
memberSveinErik9-Mar-07 7:52 
QuestionHow To Search The Item From ComboBox Pin
..HuNTeR..25-Feb-07 4:58
member..HuNTeR..25-Feb-07 4:58 
AnswerRe: How To Search The Item From ComboBox Pin
..HuNTeR..1-Mar-07 10:19
member..HuNTeR..1-Mar-07 10:19 
GeneralAn alternative method to adding items to a ComboBox Pin
jonmidd20-Feb-07 23:50
memberjonmidd20-Feb-07 23:50 
QuestionHow to Get the Value form ComboBox Pin
..HuNTeR..16-Dec-06 6:32
member..HuNTeR..16-Dec-06 6:32 
GeneralEasier way to do the same Pin
yudfgdgjkdgh1-Sep-06 0:00
memberyudfgdgjkdgh1-Sep-06 0:00 
QuestionAddValue Pin
Noferura18-Aug-06 1:28
memberNoferura18-Aug-06 1:28 
AnswerRe: AddValue Pin
datacore28-Mar-07 3:18
memberdatacore28-Mar-07 3:18 
GeneralGenerics Pin
Bjornar16-Apr-06 16:03
memberBjornar16-Apr-06 16:03 
GeneralExcellent work Pin
Damien Pitman4-Jul-05 16:51
sussDamien Pitman4-Jul-05 16:51 
Generalother tip... Pin
mainroot12-May-05 20:14
membermainroot12-May-05 20:14 
GeneralValueMember Pin
SignMan3599-Feb-05 16:47
memberSignMan3599-Feb-05 16:47 
AnswerRe: ValueMember Pin
mschrijvers14-Aug-07 1:55
membermschrijvers14-Aug-07 1:55 
GeneralNeed info....Item Selection Pin
Md Saleem Navalur4-Feb-05 6:49
memberMd Saleem Navalur4-Feb-05 6:49 
GeneralSelectedItem Pin
agir19-Jul-04 6:17
sussagir19-Jul-04 6:17 
GeneralThanks Pin
wal3360426-Feb-04 20:16
memberwal3360426-Feb-04 20:16 
GeneralNo datasource Pin
""27-May-03 1:47
member""27-May-03 1:47 
GeneralRe: No datasource Pin
Tomohiro28-May-03 2:45
memberTomohiro28-May-03 2:45 
Generalhelp me,vertically input text Pin
jirigala3-Dec-02 20:15
memberjirigala3-Dec-02 20:15 
GeneralRe: help me,vertically input text Pin
Tomohiro4-Dec-02 16:29
memberTomohiro4-Dec-02 16:29 
GeneralRe: help me,vertically input text Pin
Srinivasa Raghavan31-Mar-03 0:53
memberSrinivasa Raghavan31-Mar-03 0:53 
GeneralComboBox Items Pin
JaceII26-Nov-02 10:50
sussJaceII26-Nov-02 10:50 
GeneralRe: ComboBox Items Pin
Tomohiro26-Nov-02 21:24
memberTomohiro26-Nov-02 21:24 
GeneralStill can't assign value to Combo :( Pin
onyx19-Aug-02 4:03
memberonyx19-Aug-02 4:03 
GeneralRe: Still can't assign value to Combo :( Pin
onyx19-Aug-02 21:56
memberonyx19-Aug-02 21:56 
GeneralRe: Still can't assign value to Combo :( Pin
Tomohiro22-Aug-02 0:04
memberTomohiro22-Aug-02 0:04 
GeneralRe: Still can't assign value to Combo :( Pin
onyx22-Aug-02 0:07
memberonyx22-Aug-02 0:07 

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.

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