Fill Combobox from database

后端 未结 7 1226
北海茫月
北海茫月 2020-11-28 12:22

I have an error with a combobox

My code:

SqlConnection conn = new SqlConnection();
try
{
    conn = new SqlConnection(@\"Data Source=SHARKAWY;Initia         


        
7条回答
  •  青春惊慌失措
    2020-11-28 12:41

    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());
        }
    }
    

提交回复
热议问题