Search code examples
c#datagridviewdatarelation

DataRelation in a DataGridView


I have got a DataSet filled with two Tables:

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

And then I have got a DataRelation for these two tables. So I want to print the Student with his ID, Name and the Name of his town. That's why I create a 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);

However, when I add the DataSet to my DataGridView I always get the TownId instead of the TownName.

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

Solution

  • You missed only one thing: you need to add the appropriate column to view the data from the master table

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

    Thus, the entire code will look like this:

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