5

我有一个填充了两个表的数据集:

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。所以我想用他的身份证、姓名和他所在城镇的名字打印学生。这就是我创建 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";
4

1 回答 1

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";
于 2018-10-06T14:52:58.873 回答