This post will describe to effectively create a relationship between datatable’s in Dataset.
The following code is complete code to make relation, Let me describe it line by line.
Step 1: Get the dataset having three tables.
Step 2: Check for three tables, Please note that check is must otherwise it can raise a error.
Step 3: Now i have to make two relation’s One between table 0 and table 1 and second between table 1 and table 2.
Step 4: For two relations we need two parent columns and two child columns.
Step 5: Create Parent Datecolumn array and specify the table 0 columns which need to link with table 1 column. Similarly Create Child DataColumn array and specify corresponding table 1 Columns.
System.Data.DataColumn[] ParentColom = { ds.Tables[0].Columns["ID"], ds.Tables[0].Columns["MODULE"] };
System.Data.DataColumn[] ChildColom = { ds.Tables[1].Columns["ID"], ds.Tables[1].Columns["MODULE_NAME"] };
Step 6: Clear the old relations.
Step 7: Add relations in dataset. The first Parameter is relation name (Audit and Audit1) , Second parameter is Parentcolumn array, third parameter is child column array. fourth parameter is CreateConstraint, default is true.
- ds = bUtils.GetDataSet();
- if (ds != null && ds.Tables.Count > 2 )
- {
- System.Data.DataColumn[] ParentColom = { ds.Tables[0].Columns["ID"], ds.Tables[0].Columns["MODULE"] };
- System.Data.DataColumn[] ChildColom = { ds.Tables[1].Columns["ID"], ds.Tables[1].Columns["MODULE_NAME"] };
- System.Data.DataColumn[] ParentColom1 = { ds.Tables[1].Columns["ID"], ds.Tables[1].Columns["USER_NAME"] };
- System.Data.DataColumn[] ChildColom1 = { ds.Tables[2].Columns["ID"], ds.Tables[2].Columns["USER_NAME"] };
- ds.Relations.Clear();
- ds.Relations.Add("Audit", ParentColom, ChildColom, false);
- ds.Relations.Add("Audit1", ParentColom1, ChildColom1, false);
- }
Now you are ready with dataset relations.
Important point: Here column names are case sensitive, So Please keep every column name in capital letters at both the places (Database select statement as well as in C# code)
1 comments: