Defining Data Relation in a Dataset

We can make relationships between two tables residing within a dataset so that we can get the child records through the parent record. There are some differences and similarities between data relations and foreign keys. The child table will have only that record residing within the parent table. When we create a foreign key constraint by default the cascade rule is applied when updating and deleting records from the parent table. But in the case of a datarelation this rule can't be changed. By default, the cascade rule is applied.
 
The following code is used to define the data relationships between tables:
  1. Just go to Visual Studio 2010. 
  2. Now click on File -> New -> Project.
  3. In the new project window select Windows Forms Application.
  4. Now give the name to your project and click on ok. 
  5. Now add two datagridviewcontrols and one combox in the form. 
  6. Now add the following code:
    1. using System;  
    2. using System.Collections.Generic;  
    3. using System.ComponentModel;  
    4. using System.Data;  
    5. using System.Drawing;  
    6. using System.Linq;  
    7. using System.Text;  
    8. using System.Windows.Forms;  
    9.   
    10. namespace WindowsFormsApplication5 {  
    11.     public partial class Form1: Form {  
    12.         public Form1() {  
    13.             InitializeComponent();  
    14.         }  
    15.         DataTable dt = new DataTable();  
    16.         DataTable dtcourse = new DataTable();  
    17.         DataSet ds = new DataSet();  
    18.         private void Form1_Load(object sender, EventArgs e) {  
    19.             dt.Columns.Add(new DataColumn("sid"typeof(int)));  
    20.             dt.Columns.Add(new DataColumn("sname"typeof(string)));  
    21.             dt.Rows.Add(1, "megha");  
    22.             dt.Rows.Add(2, "isha");  
    23.             dataGridView1.DataSource = dt;  
    24.             dtcourse.Columns.Add(new DataColumn("id"typeof(int)));  
    25.             dtcourse.Columns.Add(new DataColumn("name"typeof(string)));  
    26.             dataGridView2.DataSource = dtcourse;  
    27.             ds.Tables.Add(dt);  
    28.             ds.Tables.Add(dtcourse);  
    29.             dt.PrimaryKey = new DataColumn[] { dt.Columns[0] };  
    30.             DataRelation dr = new DataRelation("stcourse", dt.Columns[0], dtcourse.Columns[0]);  
    31.             ds.Relations.Add(dr);  
    32.   
    33.         }  
    34.   
    35.         private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e {  
    36.                 DataRow[] dr = dt.Rows.Find(dataGridView1.SelectedCells[0].Value).GetChildRows("stcourse");  
    37.                 foreach(DataRow d in dr) {  
    38.                     comboBox1.Items.Add(d[1]);  
    39.                 }  
    40.             }  
    41.         }  
    42.     } 


Similar Articles