我有一个包含两个表的数据集:

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";

最佳答案

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

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";

关于c# - DataGridView中的DataRelation,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48408400/

10-10 21:08