Problems with Combobox

Asked

Viewed 53 times

0

I am developing a software that catalogues manga. In it you have the option to select 2 genres for the manga. Generos are loaded into a Combobox from a Mysql table and when the user registers the manga the genre of Combobox is written into the manga table.

In the Form I have 2 Combobox, one for each gender, but the values are not, if I select a value in cmbGenero1 this value is marked in cmbGenero2.

These were all the times that the Combobox were cited in the code:

private void inserirCmbGenero()
{
    con.Open();
    MySqlCommand comando = new MySqlCommand();
    comando.Connection = con;
    comando.CommandText = "SELECT Genero FROM tblGenero";
    MySqlDataReader dr = comando.ExecuteReader();
    DataTable dt = new DataTable();
    dt.Load(dr);
    cmbGenero1.DisplayMember = "Genero";
    cmbGenero1.DataSource = dt;
    cmbGenero2.DisplayMember = "Genero";
    cmbGenero2.DataSource = dt;
    con.Close();
}

private void frmCadastro_Load(object sender, EventArgs e)
{
    inserirCmbMangaka();
    inserirCmbGenero();
}

1 answer

1


You are using the same context for both combobox. You need a context for each. See about this here. and an answer in the OS here

Below the solution to your problem.

USING cmbGenero2.Bindingcontext = new Bindingcontext();

private void inserirCmbGenero()
{
    SqlConnectionStringBuilder sConnB = new SqlConnectionStringBuilder()
    {
            DataSource = "MYSERVER",
            InitialCatalog = "Testes",
            UserID = "user_tst",
            Password = "user_tst"
    };


    using (var con = new SqlConnection(sConnB.ConnectionString))
    {
        con.Open();
        SqlCommand comando = new SqlCommand();
        comando.Connection = con;
        comando.CommandText = "SELECT ID_GENERO, DESC_GENERO FROM TBLGENERO";
        SqlDataReader dr = comando.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);
        cmbGenero1.DisplayMember = "DESC_GENERO";
        cmbGenero1.ValueMember = "ID_GENERO";
        cmbGenero1.DataSource = dt;

        cmbGenero2.BindingContext = new BindingContext();
        cmbGenero2.DisplayMember = "DESC_GENERO";
        cmbGenero2.ValueMember = "ID_GENERO";
        cmbGenero2.DataSource = dt;

    }

}
  • Vlw bro, it worked out here. If you want to let me know I’ll give you the software when it’s ready.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.