Sponsored Ad

Saturday, March 6, 2010

How to Create Relations in C# Dataset | Relations between DataTable’s

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.

 

Code Snippet
  1. ds = bUtils.GetDataSet();
  2.  
  3.         if (ds != null && ds.Tables.Count > 2 )
  4.         {
  5.             System.Data.DataColumn[] ParentColom = { ds.Tables[0].Columns["ID"], ds.Tables[0].Columns["MODULE"] };
  6.             System.Data.DataColumn[] ChildColom = { ds.Tables[1].Columns["ID"], ds.Tables[1].Columns["MODULE_NAME"] };
  7.  
  8.             System.Data.DataColumn[] ParentColom1 = { ds.Tables[1].Columns["ID"], ds.Tables[1].Columns["USER_NAME"] };
  9.             System.Data.DataColumn[] ChildColom1 = { ds.Tables[2].Columns["ID"], ds.Tables[2].Columns["USER_NAME"] };
  10.  
  11.             ds.Relations.Clear();
  12.  
  13.             ds.Relations.Add("Audit", ParentColom, ChildColom, false);
  14.             ds.Relations.Add("Audit1", ParentColom1, ChildColom1, false);
  15.         }

 

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:

  1. That's good stuff, thanks for posting it. Would be great to see a follow up showing the potential for using the relationships once they've been established.
    ReplyDelete

Sponsored Ad

More Related Articles

Website Update

Followers