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:
using System;
using SystemCollections.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]); } }
}
Student and passionate about technologies to learn and share
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: