I am running nested foreach, where first I want to get all id and then for each id I want to populate datagridview, but the it is returning only first id six times. (my tables has only six data rows). Ran diagnostics with breakpoints, DataTable dt0 has all ids, but DataTable dt2 has only first id. same goes for other var.
int id = 0;
int price = 0;
int qty = 0;
private void button1_Click(object sender, EventArgs e)
{
con.Open();
string sql = "SELECT id FROM tbl_price ";
SqlCommand cmd0 = new SqlCommand(sql, con);
SqlDataAdapter dAdapter0 = new SqlDataAdapter(cmd0);
DataTable dt0 = new DataTable();
dAdapter0.Fill(dt0);
if (dt0.Rows.Count > 0)
{
foreach (DataRow dr in dt0.Rows)
{
SqlCommand cmd2 = new SqlCommand("SELECT P.id, P.price, Q.qty FROM tbl_price P INNER JOIN tbl_qty Q ON P.id=Q.id WHERE P.id='" + dt0.Rows[0]["id"] + "' ", con);
SqlDataAdapter dAdapter2 = new SqlDataAdapter(cmd2);
DataTable dt2 = new DataTable();
dAdapter2.Fill(dt2);
id = Convert.ToInt32(dt2.Rows[0]["id"]);
price = Convert.ToInt32(dt2.Rows[0]["price"]);
qty = Convert.ToInt32(dt2.Rows[0]["qty"]);
int n = dataGridView1.Rows.Add();
dataGridView1.Rows[n].Cells["dgid"].Value = id;
dataGridView1.Rows[n].Cells["dgprice"].Value = price;
dataGridView1.Rows[n].Cells["dgqty"].Value = qty;
}
}
con.Close();
}
//Below is my result in Datagridview
id qty price
1 100 10
1 100 10
1 100 10
1 100 10
1 100 10
1 100 10