Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill Combobox from database

I have an error with a combobox

My code:

SqlConnection conn = new SqlConnection();
try
{
    conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456");
    string query = "select FleetName, FleetID from fleets";
    SqlCommand cmd = new SqlCommand(query, conn);
    cmd.CommandText = query;
    conn.Open();
    SqlDataReader drd = cmd.ExecuteReader();
    while (drd.Read())
    {
         cmbTripName.Items.Add(drd["FleetName"].ToString());
         cmbTripName.ValueMember = drd["FleetID"].ToString();
         cmbTripName.DisplayMember = drd["FleetName"].ToString();
    }
}
catch
{
     MessageBox.Show("Error ");
}

The data is presented in the combobox, but when you change the selection valuemember the displaymember does not change.

It's working now but when I click the button to show the data

private void button1_Click(object sender, EventArgs e)
{
    label1.Text = cmbTripName.DisplayMember;
    label2.Text = cmbTripName.ValueMember;
}

This is displayed:

FleetName
FleetID

It does not display the value

like image 473
Ahmed Sharkawy Avatar asked Sep 19 '12 12:09

Ahmed Sharkawy


2 Answers

You will have to completely re-write your code. DisplayMember and ValueMember point to columnNames! Furthermore you should really use a using block - so the connection gets disposed (and closed) after query execution.

Instead of using a dataReader to access the values I choosed a dataTable and bound it as dataSource onto the comboBox.

using (SqlConnection conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456"))
{
    try
    {
        string query = "select FleetName, FleetID from fleets";
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        conn.Open();
        DataSet ds = new DataSet();
        da.Fill(ds, "Fleet");
        cmbTripName.DisplayMember =  "FleetName";
        cmbTripName.ValueMember = "FleetID";
        cmbTripName.DataSource = ds.Tables["Fleet"];
    }
    catch (Exception ex)
    {
        // write exception info to log or anything else
        MessageBox.Show("Error occured!");
    }               
}

Using a dataTable may be a little bit slower than a dataReader but I do not have to create my own class. If you really have to/want to make use of a DataReader you may choose @Nattrass approach. In any case you should write a using block!

EDIT

If you want to get the current Value of the combobox try this

private void cmbTripName_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbTripName.SelectedItem != null)
    {
        DataRowView drv = cmbTripName.SelectedItem as DataRowView;

        Debug.WriteLine("Item: " + drv.Row["FleetName"].ToString());
        Debug.WriteLine("Value: " + drv.Row["FleetID"].ToString());
        Debug.WriteLine("Value: " + cmbTripName.SelectedValue.ToString());
    }
}
like image 189
Pilgerstorfer Franz Avatar answered Oct 20 '22 17:10

Pilgerstorfer Franz


To use the Combobox in the way you intend, you could pass in an object to the cmbTripName.Items.Add method.

That object should have FleetID and FleetName properties:

while (drd.Read())
{
    cmbTripName.Items.Add(new Fleet(drd["FleetID"].ToString(), drd["FleetName"].ToString()));
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";

The Fleet Class:

class Fleet
{
     public Fleet(string fleetId, string fleetName)
     {
           FleetId = fleetId;
           FleetName = fleetName
     }
     public string FleetId {get;set;}
     public string FleetName {get;set;}
}

Or, You could probably do away with the need for a Fleet class completely by using an anonymous type...

while (drd.Read())
{
    cmbTripName.Items.Add(new {FleetId = drd["FleetID"].ToString(), FleetName = drd["FleetName"].ToString()});
}
cmbTripName.ValueMember = "FleetId";
cmbTripName.DisplayMember = "FleetName";
like image 43
Nattrass Avatar answered Oct 20 '22 18:10

Nattrass