简体   繁体   中英

Populate DataGridview upon ComboBox selection

I have a DataGridView that is populated on the load of the form. I have a ComboBox filled too on the load of the form. What I need is when I change the value of the ComboxBox the DataGridView is populated again but depending on the value I selected on the ComboBox .

Right now it is giving me an error that

the conection is already open .

This is the code I have right now.(I´m using windows forms).

Any Ideas on what I´m doing wrong?

private void Form1_Load(object sender, EventArgs e)
{
    poputateCombo();
    populateDatagridView(s);
}

private void populateDatagridView(string s)
{
    try
    {
        string query = "SELECT "values" FROM "table" WHERE seccao = '" + s + "'  ";
        conexao.Open();
        MySqlDataAdapter sda = new MySqlDataAdapter(query, conexao);
        DataTable dt1;  dt1 = new DataTable();
        sda.Fill(dt1);
        BindingSource  bsource = new BindingSource();
        bsource.DataSource = dt1;
        dgPlus.DataSource = bsource;
        sda.Update(dt1);
        conexao.Close();
    }
    catch (MySqlException er)
    {
        MessageBox.Show("Error:" + er.ToString());
    }
}

private void cbSeccoes_SelectedIndexChanged(object sender, EventArgs e)
{
    povoaPlus(cbSeccoes.Text);
}

You can not open the connection when its already in open state. So check if connection state is not open then only call the conexao.Open();

if(!(conn.State == ConnectionState.Open))
    conexao.Open()

Second thing, your code syntax is not looking correct.

string query = "SELECT "values" FROM "table" WHERE seccao = '" + s + "'  ";

Above line will not even compile.

You may want write this

string query = "SELECT values FROM table WHERE seccao = '" + s + "'  ";

Or if you are trying to send the column name and Table name with the help of variable then it would be

string query = "SELECT " + values +" FROM " + table +" WHERE seccao = '" + s + "'  ";

Even this will compile but I would not suggest you to use this. Instead of this use parameterized query to avoid the SqlInjection

In your combobox's SelectedIndexChanged even call the method which binds the datagridview.

private void cbSeccoes_SelectedIndexChanged(object sender, EventArgs e)
{
    // I'm not sure what does this method work
    //povoaPlus(cbSeccoes.Text);

    // I think you should call this    
    populateDatagridView(string s)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM