search inside two access tables from C# form

94 Views Asked by At

this is my code, How can I search inside Table1 and Table2 with same textbox1.text value, by the other words:

// [Table1]

| name     | age            |
| -------- | -------------- |
| aaa      | 12             |
| bbb      | 13             |
| ccc      | 14             |

//     [Table2]
| name     | gender         |
| -------- | -------------- |
| aaa      | male           |
| bbb      | female         |
| ccc      | male           |

How can I get age and gender values and display it inside txt.Text when [name] equal to textbox1.text?

thanks

 con.Open();
            // search inside table1
            OleDbCommand da = new OleDbCommand("SELECT * FROM [Table1] WHERE Table1.name='@name",con);
 
           //search inside table2
            OleDbCommand da2 = new OleDbCommand("SELECT * FROM [Table2] WHERE Table2.name='@name", con);
            
            // give @name value to table1 and table2 as parameters
            da.Parameters.AddWithValue("@name",textBox1.Text);
            da2.Parameters.AddWithValue("@name", textBox1.Text);

            // its time for executing 
            OleDbDataReader dr = da.ExecuteReader();
            OleDbDataReader dr2 = da2.ExecuteReader();

            // now display it in textBox as a string
            if (dr.Read())
            {
                dr2.Read();
                for (int x = 0; x < 4;x++ ) {
                    if(dr[x].ToString() !=""){

                        txt.Text += dr[x].ToString() + System.Environment.NewLine;
                    }
                }
            }
            else { MessageBox.Show("error"); }
            con.Close();
1

There are 1 best solutions below

6
Caius Jard On BEST ANSWER

To join the data together and restrict to just what is written in a textbox and display in a datagridview Control:

using(var da = new OleDbDataAdapter("SELECT FROM Table1 t1 INNER JOIN Table2 t2 ON t1.Name = t2.Name WHERE t1.name=@name", con)){
    da.SelectCommand.Parameters.AddWithValue("@name",textBox1.Text);

    var dt = new DataTable();
    da.Fill(dt);

    someDataGridView.DataSource = dt;
}

It's literally all you need to do; the dataadapter will open the connection etc; just write an sql, add parameters, fill a datatable, assign the table to be the DataSource of a grid (you'll need to add a datagridview to your form and name it and adjust the code name)