How to fill two different datagrid from one mysql table in c#

107 views Asked by At

I have a problem in my application. I'm tying to fill two different DataGrids in C#, using WPF, from one mysql table.

I don't know how to do this properly. Below is my sample code, which does not work. It currently only fills czesciTables, but not czesciTables2.

I've been researching how to do this, but google only shows me results from other sources.

try
{
    for (int i = 0; i <= 4; i++ )
    {
        connection.Open();
        MySqlCommand cmd = new MySqlCommand("SELECT id_czesci_symbol AS KOD,
                                                    ilosc AS ILOSC
                                             FROM `test`.`zamowienie`
                                             WHERE z_numer_naprawy='" + numberBox.Content.ToString() + "'
                                             ORDER BY ilosc LIMIT 5;", connection);
        MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds, "LoadDataBinding");
        czesciTable.DataContext = ds;
    }

    for (int i = 5; i <= 9; i++)
    {
        connection.Open();
        MySqlCommand cmd2 = new MySqlCommand("SELECT id_czesci_symbol AS KOD,
                                                     ilosc AS ILOSC
                                              FROM `test`.`zamowienie`
                                              WHERE z_numer_naprawy='" + numberBox.Content.ToString() + "'
                                              ORDER BY ilosc LIMIT 5;", connection);
        MySqlDataAdapter adp2 = new MySqlDataAdapter(cmd2);
        DataSet ds2 = new DataSet();
        adp2.Fill(ds2, "LoadDataBinding");
        czesciTable2.DataContext = ds2;
    }
}
catch (MySqlException ex) 
{
     MessageBox.Show(ex.ToString());
}
finally 
{
     connection.Close();
}
1

There are 1 answers

3
RealSollyM On

To answer your question directly, here's the sample code below.

try
{
    for (int i = 0; i <= 9; i++ )
    {
        connection.Open();
        MySqlCommand cmd = new MySqlCommand("SELECT id_czesci_symbol AS KOD,
                                                    ilosc AS ILOSC
                                             FROM `test`.`zamowienie`
                                             WHERE z_numer_naprawy='" + numberBox.Content.ToString() + "'
                                             ORDER BY ilosc LIMIT 5;", connection);
        MySqlDataAdapter adp = new MySqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds, "LoadDataBinding");
        if (i < 5)
            czesciTable.DataContext = ds;
        else
            czesciTable2.DataContext = ds;

        cmd.Dispose();
        adp.Dispose();
    }
}catch (MySqlException ex) {
     MessageBox.Show(ex.ToString());
}finally {
     connection.Close();
}

What is is that you are trying to archive? Perhaps we can help you get the better solution to your problem.