Click here to Skip to main content
15,848,319 members
Please Sign up or sign in to vote.
4.50/5 (2 votes)
See more:
populating the combox and displaying the value in the combobox
for eg. if I choose name in the combobox the corresponding ID should display in the text box . Do anybody know? I am learning c#. I tried it can anybody examine the following code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
namespace DBExample
    public partial class Form1 : Form
        private OleDbConnection dbConn; // Connection object
        private OleDbCommand dbCmd;     // Command object
        private OleDbDataReader dbReader;// Data Reader object
        private Member aMember;
        private string sConnection;
        // private TextBox tb1;
        // private TextBox tb2;
        private string sql;
        public Form1()
        private void Form1_Load(object sender, EventArgs e)
                // Construct an object of the OleDbConnection
                // class to store the connection string
                // representing the type of data provider
                // (database) and the source (actual db)
                sConnection =
                    "Provider=Microsoft.Jet.OLEDB.4.0;" +
                    "Data Source=c:member.mdb";
                dbConn = new OleDbConnection(sConnection);
                // Construct an object of the OleDbCommand
                // class to hold the SQL query. Tie the
                // OleDbCommand object to the OleDbConnection
                // object
                sql = "Select * From memberTable Order " +
                      "By LastName , FirstName ";
                dbCmd = new OleDbCommand();
                dbCmd.CommandText = sql;
                dbCmd.Connection = dbConn;
                // Create a dbReader object
                dbReader = dbCmd.ExecuteReader();
                while (dbReader.Read())
                    aMember = new Member
                    // tb1.Text = dbReader["FirstName"].ToString();
                    // tb2.Text = dbReader["LastName"].ToString();
                    // tb1.Text = aMember.X().ToString();

                    //tb2.Text = aMember.Y(aMember.ID).ToString();

                    // this.listBox1.Items.Add(aMember.ToString());
                    // MessageBox.Show(aMember.ToString());
                    // Console.WriteLine(aMember.ToString());
            catch (System.Exception exc)
                MessageBox.Show("show" + exc);
        private void DbGUI_Load(object sender, EventArgs e)

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
            this.textBox1.Text = comboBox1.SelectedItem.ToString();
            //textBox2.Text = string.Empty;
            foreach (var Item in comboBox1.Items);
            textBox2.Text += aMember.ID.ToString();
            //MessageBox.Show("read one record");
        private void textBox2_TextChanged(object sender, EventArgs e)
        private void textBox1_TextChanged(object sender, EventArgs e)
Updated 10-Mar-11 8:16am
Mary Abraham 10-Mar-11 22:27pm    
Thanks.Still I ?Have a problem. it is showing the expection error.

The way that you've written it, you will never be able to find out the id. The reason is that after you created the new Member object, you didn't maintain the reference to it. You added an item to the comboBox, but you just added a clone of the string.

So there are a couple of ways to do this. One is to override the ToString method of the Member class itself. As in:

class Member
  //other properties and methods

  protected override string ToString()
    return this.FirstName;

Then, instead of adding aMember.FirstName.ToString() to the ComboBox, you add the Member object as in this.comboBox1.Items.Add(aMember);. Then, when an item is selected you could just set the TextBox to ((Member)(comboBox1.SelectedItem)).ID. And, the combobox will use the ToString method to set the selected text and the text for each drop down.

Or, you could use a BindingList<t></t>. In that case, you create a new list like:

BindingList<Member> comboBoxList = new BindingList<Member>();

Then add the new items to the BindingList.

Then, you set the comboBox1 binding properties as in:
comboBox1.DataSource = comboBoxList;
comboBox1.DisplayMember = "FirstName";
comboBox1.ValueMember = "ID";

(You just have to make sure that FirstName and ID are actually properties and not just public fields.)

Then in the SelectedIndexChanged event, you set the TextBox Text field to comboBox1.SelectedValue.ToString().
Share this answer
Dalek Dave 13-Mar-11 18:51pm    
Good Answer
Looks like you know how to get data from a database so i'll just state what you need to do. Am sorry I haven't put real code coz am actually sending this from my phone so formating is tricky.
Create a new event handler method for the combo box that contains names. The handler should handle the "Selected Index Changed" event.
Within this method you'll create an sql code to get the id that matches the selected name. Something like >select id from [table name] where name=' " + combobox1.Text + " ' <<br mode="hold" />you pass this sql into the oleDbCommand object via the command text property.
You then perform a query through the method command.ExecuteReader()
use the reader object to display the id into a textbox

Share this answer
William Winner 10-Mar-11 14:52pm many bad or inefficient things...

First, never do: "select id from [table name] where name='" + combobox1.Text + "'". You're setting yourself up for SQL injection attacks.

Second, if you are only pulling out one value, you wouldn't use ExecuteReader, but ExecuteScalar.

And finally, she's already pulled out the ID information, so why query that again from the database?
wizardzz 10-Mar-11 16:49pm    
Good call Will, sounds like you're really Winning today.
Mwanzia_M 11-Mar-11 7:55am    
I stand corrected knowing that am not the best coz am just getting a grip of c#. Could you please tell me how I can prevent an sql injection? I know one way is to prevent string concatenation but then what do I put in the sql code in the section (select id from [table] where id = ' " + somevalue + " ' ) . Ignore the previous problem and assume all we need is an id where the name is the value of a combo box and no prior filter has been done.
Please help.
'This will insert class in your combo box
'your database contain one borad table and one class table
'depending on boardid class will selected from database.
' _cmbclass-This is your combo box name
'pass any boardid

Private Function getClass(ByVal _cmbclass As ComboBox, ByVal boardID As String) As String
       Dim ClassDataSet As New DataSet
       Dim c_adapter As OleDb.OleDbDataAdapter
       If conn.State = ConnectionState.Closed Then
           commd.CommandText = "select className,ClassID from cc_class where BoardID = " & boardID & ""
           commd.Connection = conn
           c_adapter = New OleDb.OleDbDataAdapter(commd)
           c_adapter.Fill(ClassDataSet, "cc_class")
           _cmbclass.DataSource = ClassDataSet.Tables(0)
           _cmbclass.ValueMember = "ClassID"
           _cmbclass.DisplayMember = "className"
       End If
       Return getClass
   End Function

'all the data will fill in your combo box
'Add the following code to get id in your text box

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900