简体   繁体   中英

How to filter data from tables and display it in DataGridView?

I am new to C# and SQL.

截图

As show in screenshot, I am trying to filter data from multiple tables and insert it into the DataDridView. I have 3 tables:

  • Orders.

  • Order_Details

  • Products.

I want to filter order_Id 2 (Sam), I want to display what did he order into DataGridView based on his order_ID. I want to display his data as follow:

  • customer name
  • product name
  • Qty
  • price

According to my code, I know how to display the "Order_details" table but I do not know how to display Sam' order details into DataGridView. I maean I want to extract data of Sam from the 3 tables and show it in the DataGridView. please help me how to achieve this. Thank you

private void button1_Click(object sender, EventArgs e)

    {   // display Order_details table into DataGridView

        SqlConnection con = new SqlConnection("Data Source=PCN11-TOSH;Initial Catalog=mydb;Integrated Security=True");
        con.Open();
        SqlCommand cm = new SqlCommand("SELECT *FROM Order_details");
        cm.Connection = con;

        SqlDataAdapter da = new SqlDataAdapter(cm);
        DataTable dt = new DataTable();
        da.Fill(dt);

        con.Close();

        dataGridView1.DataSource = dt;

}

You need to use join and then select data from database and bind it to gridview.

select Distinct o.customer_name,od.qty,p.product_name,p.price from orders o
inner join order_details od on o.orderid=od.orderid
inner join products p on p.productid=od.product_id
where o.order_id=1

Oh I'm not as shy about giving out homework answers. This is more a SQL question than a C# question. If you wanted to solve this with code, I'd implement a ORM and shape your data into the Grid using LINQ. Since your original question involves only a SqlAdapter, the answer lies in the query.

private void button1_Click(object sender, EventArgs e)

    {   // display Order_details table into DataGridView

        SqlConnection con = new SqlConnection("Data Source=PCN11-TOSH;Initial Catalog=mydb;Integrated Security=True");
        con.Open();
        SqlCommand cm = new SqlCommand(@"SELECT o.customer_name, p.product_name, d.Qty, p.price FROM Orders
                                         JOIN order_details d ON d.order_ID = o.order_ID
                                         JOIN products p ON p.product_ID = d.product_ID");
        cm.Connection = con;

        SqlDataAdapter da = new SqlDataAdapter(cm);
        DataTable dt = new DataTable();
        da.Fill(dt);

        con.Close();

        dataGridView1.DataSource = dt;

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