在Windows应用程序GridView中显示外键数据

时间:2013-02-20 13:02:53

标签: c# .net datagridview

我有两张桌子

'Item Catagory' with fields

CatagoryId

CatagoryName

Items

带字段

ItemId

CatagoryId

现在Item Form我希望在Item

中显示DataGridView数据

我想从GridView Columm中的CatogoryName表中显示ItemCatogory

目前我无法做到这一点,任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

与gridview绑定的查询应该是这样的。

SELECT Items.ItemId, ItemCatogory.CatogoryName FROM Items JOIN ItemCatogory USING(CatagoryId)

以下是执行此操作的示例代码:

using System.Data;
using System.Data.SqlClient;

然后

SqlDataAdapter da;
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
static SqlConnection oc = new SqlConnection(@"Data Source=xxxx;Network Library=DBMSSOCN;Initial Catalog=xxxx;User Id=xxxx;Password=xxxx;");
cmd.CommandText = "SELECT Items.ItemId, ItemCatogory.CatogoryName FROM Items JOIN ItemCatogory USING(CatagoryId)";

oc.Open();
cmd.Connection = oc;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
cmd.ExecuteNonQuery();

GridView1.DataSource = ds;

GridView1.DataBind();

oc.Close();
相关问题