从DatagridView中的两个表中获取列
本文关键字:两个 获取 DatagridView | 更新日期: 2023-09-27 17:54:11
我有两个表,我想在我的DatagridView
(Data1)添加列
mycon.Open();
SqlCommand cmd = new SqlCommand("SELECT ItemName,Price1 FROM Pharmacy_Items", mycon);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Data1.Rows.Add();
Data1.Rows[x].Cells[0].Value = reader["ItemName"].ToString();
Data1.Rows[x].Cells[1].Value = reader["Price1"].ToString();
x++;
}
mycon.Close();
现在我想从另一个表添加一列到我的DatagridView (Data1.Rows[x].Cells[2].Value
)。我怎样才能做到这一点呢?
我是SQL新手。:)
只需更改您的查询,与您需要的表JOIN并添加您想要显示的新列。示例如下:
mycon.Open();
SqlCommand cmd = new SqlCommand("SELECT p.ItemName, p.Price1, o.ColumnFromOtherTable FROM Pharmacy_Items p INNER JOIN OtherTable o ON p.ID = o.ID", mycon);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Data1.Rows.Add();
Data1.Rows[x].Cells[0].Value = reader["ItemName"].ToString();
Data1.Rows[x].Cells[1].Value = reader["Price1"].ToString();
Data1.Rows[x].Cells[2].Value = reader["ColumnFromOtherTable"].ToString();
x++;
}
mycon.Close();