DataGridView中的DataRelation

时间:2018-01-23 18:21:19

标签: c# datagridview datarelation

我有一个填充了两个表的DataSet:

dbSet = new DataSet();
//DataTable and DataRelation
DataTable dtStudent = new DataTable("Student");


//fill datatable 1
dtStudent.Columns.Add("Id", typeof(int));
dtStudent.Columns.Add("Name", typeof(string));
dtStudent.Columns.Add("TownId", typeof(int));

dtStudent.Rows.Add(new object[] { 1, "Arthur", 1 });
dtStudent.Rows.Add(new object[] { 2, "Stefan", 2 });


DataTable dtTown = new DataTable("Town");
dtTown.Columns.Add("Id", typeof(int));
dtTown.Columns.Add("Name", typeof(string));

dtTown.Rows.Add(new object[] { 1, "KW",});
dtTown.Rows.Add(new object[] { 2, "Perg", });

dbSet.Tables.Add(dtStudent);
dbSet.Tables.Add(dtTown);

然后我有这两个表的DataRelation。 所以我想用他的ID,姓名和他的城镇名称打印学生。 这就是我创建DataRelation的原因。

//DataRelation
DataColumn parentCol, childCol;
childCol = dbSet.Tables["Town"].Columns["Id"];
parentCol = dbSet.Tables["Student"].Columns["TownId"];

DataRelation dr;
dr = new DataRelation("DataRelation", parentCol, childCol);

dbSet.Relations.Add(dr);

但是,当我将DataSet添加到DataGridView时,我总是得到 TownId 而不是 TownName

dgv.DataSource = dbSet;
dgv.DataMember = "Student";

1 个答案:

答案 0 :(得分:2)

您只错过了一件事:您需要添加适当的列以查看主表中的数据

dbSet.Tables["Student"].Columns.Add("Town", dbSet.Tables["Town"].Columns["Name"].DataType, "Parent.Name");

因此,整个代码将如下所示:

dbSet = new DataSet();
//DataTable and DataRelation
DataTable dtStudent = new DataTable("Student");


//fill datatable 1
dtStudent.Columns.Add("Id", typeof(int));
dtStudent.Columns.Add("Name", typeof(string));
dtStudent.Columns.Add("TownId", typeof(int));

dtStudent.Rows.Add(new object[] { 1, "Arthur", 1 });
dtStudent.Rows.Add(new object[] { 2, "Stefan", 2 });


DataTable dtTown = new DataTable("Town");
dtTown.Columns.Add("Id", typeof(int));
dtTown.Columns.Add("Name", typeof(string));

dtTown.Rows.Add(new object[] { 1, "KW",});
dtTown.Rows.Add(new object[] { 2, "Perg", });

dbSet.Tables.Add(dtStudent);
dbSet.Tables.Add(dtTown);

//DataRelation
DataColumn parentCol, childCol;
childCol = dbSet.Tables["Town"].Columns["Id"];
parentCol = dbSet.Tables["Student"].Columns["TownId"];

DataRelation dr;
dr = new DataRelation("DataRelation", parentCol, childCol);
dbSet.Relations.Add(dr);

dbSet.Tables["Student"].Columns.Add("Town", dbSet.Tables["Town"].Columns["Name"].DataType, "Parent.Name");


//Datagridview
dgv.DataSource = dbSet;
dgv.DataMember = "Student";