Loading combobox from database in C#

Humpy picture Humpy · Jul 31, 2012 · Viewed 20.1k times · Source

I am creating an application, where I can add a customer's first name, last name, email, the date, service type (pc repair), the technician PC brand, pc type, type of OS, and the problem with the computer. I am able to insert data into the MySQL database using phpMyAdmin.

However, I a stuck on this part. I am trying to view the service order that was just created. I would like to load the combobox by the last name of the customer, and once I click on the customer's name, it populates all the fields that were mentioned above and the service number that it was inserted into the database. I am having issues loading the combobox and texfields.

Any ideas are appreciated! If a combobox is a bad idea and there is a better way, please let me know! I tried this code, but SQLDataAdapter is not working for me. I somehow can't find an example that I can relate too.

private void cbViewServices_SelectedIndexChanged(object sender, EventArgs e)
{
  if (cbViewServices.SelectedIndex >- 1)
  {
    string lastName = cbViewServices.SelectedValue.ToString();                
    MySqlConnection conn = new MySqlConnection("server=localhost;uid=******;password=**********;database=dboserviceinfo;");
    conn.Open();

    SqlDataAdapter da = new SqlDataAdapter("select distinct LastName from tserviceinfo where LastName='" + lastName + "'", conn);

    DataSet ds = new DataSet();
    da.Fill(ds); conn.Close();
  }
}

Answer

cubski picture cubski · Jul 31, 2012

I do not recommend using the 'Lastname' as a parameter to load your details since that field most likely isn't unique. Unless that is the case in your program.

This sample does the following:

  1. Load customer ID (or lastname in your case) to a combobox.
  2. Handle the combobox's change event and pass it as a parameter to a method that will use that to load the details.
  3. Load the customer details using the passed parameter.

A couple of guidelines:

  1. Enclose disposable objects in a 'using' statement so it will be disposed properly.
  2. Do not use string concatenation to create your SQL statements. Use SQL parameters instead, that way you'll avoid SQL injection and make your code clearer.
  3. Take a look at MySQL .NET connector provider documentation for best practices.

    //Load customer ID to a combobox
    private void LoadCustomersId()
    {
        var connectionString = "connection string goes here";
        using (var connection = new MySqlConnection(connectionString))
        {
            connection.Open();
            var query = "SELECT Id FROM Customers";
            using (var command = new MySqlCommand(query, connection))
            {
                using (var reader = command.ExecuteReader())
                {
                    //Iterate through the rows and add it to the combobox's items
                    while (reader.Read())
                    {
                        CustomerIdComboBox.Items.Add(reader.GetString("Id"));    
                    }
                }    
            }
        }
    }
    
    //Load customer details using the ID
    private void LoadCustomerDetailsById(int id)
    {
        var connectionString = "connection string goes here";
        using (var connection = new MySqlConnection(connectionString))
        {
            connection.Open();
            var query = "SELECT Id, Firstname, Lastname FROM Customer WHERE Id = @customerId";
            using (var command = new MySqlCommand(query, connection))
            {
                //Always use SQL parameters to avoid SQL injection and it automatically escapes characters
                command.Parameters.AddWithValue("@customerId", id);
                using (var reader = command.ExecuteReader())
                {
                    //No customer found by supplied ID
                    if (!reader.HasRows)
                        return;
    
                    CustomerIdTextBox.Text = reader.GetInt32("Id").ToString();
                    FirstnameTextBox.Text = reader.GetString("Firstname");
                    LastnameTextBox.Text = reader.GetString("Lastname");
                }
            }
        }
    }
    
    //Pass the selected ID in the combobox to the customer details loader method 
    private void CustomerIdComboBox_SelectedIndexChanged(object s, EventArgs e)
    {
        var customerId = Convert.ToInt32(CustomerIdComboBox.Text);
        LoadCustomerDetailsById(customerId);
    }
    

I'm not entirely sure if this is what your looking for but most of the guidelines still applies.

Hope this helps!