Defining Data Relation in a Dataset

We can make relationships between two tables residing within the a dataset so that we can get the child records through the parent record. There are some differences and similarity between data relation and foreign key. 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 relation 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:

    using System;

    using System
    Collections.Generic;

    using
    System.ComponentModel;
    using
    System.Data;
    using
    System.Drawing;
    using
    System.Linq;
    using
    System.Text;
    using
    System.Windows.Forms;

    namespace
    WindowsFormsApplication5
    {

        public partial class Form1 : Form
       
    {
           
    public Form1()
           
    {
               
    InitializeComponent();
           
    }
           
    DataTable dt = new DataTable();
           
    DataTable dtcourse = new DataTable();
           
    DataSet ds = new DataSet();
           
    private void Form1_Load(object sender, EventArgs e)
           
    {
               
    dt.Columns.Add(new DataColumn("sid", typeof(int)));
               
    dt.Columns.Add(new DataColumn("sname",typeof(string)));
               
    dt.Rows.Add(1,"megha");
               
    dt.Rows.Add(2,"isha");
               
    dataGridView1.DataSource = dt;
               
    dtcourse.Columns.Add(new DataColumn("id",typeof(int)));
               
    dtcourse.Columns.Add(new DataColumn("name", typeof(string)));
               
    dataGridView2.DataSource = dtcourse;
               
    ds.Tables.Add(dt);
               
    ds.Tables.Add(dtcourse);
               
    dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
               
    DataRelation dr=new DataRelation("stcourse",dt.Columns[0],dtcourse.Columns[0]);
               
    ds.Relations.Add(dr);

           
    }

            private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e
                {

               
    DataRow[] dr = dt.Rows.Find(dataGridView1.SelectedCells[0].Value).GetChildRows("stcourse");
               
    foreach (DataRow d in dr)
               
    {
                   
    comboBox1.Items.Add(d[1]);
               
    }
           
    }

        }

    }


Up Next
    Ebook Download
    View all
    Learn
    View all