Ren
Ren

Reputation: 775

Retrieve records from Mysql database and display it in a combo box

I have a DbConnect class which queries a MySQL database and store the results into a datatable - something like this:

public DataTable selectCombo()
{
        string query = "SELECT DISTINCT month FROM printer_count";

        if (this.OpenConnection() == true)
        {
            MySqlCommand cmd = new MySqlCommand(query, connection);
            DataTable dt = new DataTable();
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
        }

        this.CloseConnection();
        return dt;
 }

Now how to retrieve the datatable from the class into the combo box main form? Can I do something like this?

ComboBox1.DataSource = dbConnect();
ComboBox1.DisplayMember = "Name";    // column name to display

Upvotes: 1

Views: 461

Answers (1)

Steve
Steve

Reputation: 216353

You have two variables with the same name. (dt) One is defined as a string, the other one inside the if block is defined as a datatable. You return the empty string and this, of course, cannot work when you try to assign the DataSource of the combo

public DataTable selectCombo()
{
       DataTable dt = new DataTable();
       string query = "SELECT DISTINCT month FROM printer_count";
        if (this.OpenConnection() == true)
        {

            MySqlCommand cmd = new MySqlCommand(query, connection);
            MySqlDataAdapter da = new MySqlDataAdapter(cmd);
            da.Fill(dt);
        }

       this.CloseConnection();
       return dt;
 }

Now you could write

....
ComboBox1.DisplayMember = "Name";
ComboBox1.DataSource = selectCombo();
.....

Also this code is not very safe. If, for any reason, you get an exception, the CloseConnection will not be called leaving an open connection around and this is very problematic for the stability of your system. However, fixing that problem, requires a different approach to you OpenConnection code. Instead of true this method should return the MySqlConnection object so your calling code could apply the using statement around the connection instance

Upvotes: 1

Related Questions