简体   繁体   中英

Displaying foreign key data in Windows Application GridView

I have two Tables

'Item Catagory' with fields

CatagoryId

and

CatagoryName

and Items

with fields

ItemId

and

CatagoryId

Now on Item Form I want to Display Item Data in A DataGridView

I want to Display CatogoryName From ItemCatogory Table in a GridView Columm

Currently I am not able to do that, Can Any One Help me in this Regard ???

Your Query to bind with gridview should be like this.

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

Here is a sample code to do this:

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

then

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();

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