Friday, September 17, 2010

Using binding context with 2 tables in C#

       
....
DataTable dt = new DataTable("One");
DataTable dt1 = new DataTable("Two");
DataSet ds = new DataSet();
private void Form1_Load(object sender, EventArgs e)
{
dt.Columns.Add("No");
dt.Columns.Add("Name");
dt.PrimaryKey = new DataColumn[] {dt.Columns[0] };
dt.Rows.Add("1", "A");
dt.Rows.Add("2", "B");


dt1.Columns.Add("No");
dt1.Columns.Add("Address");

dt1.Rows.Add("1", "Local address");
dt1.Rows.Add("2", "Postal address");
dt1.Rows.Add("2", "Local address");


ds.Tables.Add(dt);
ds.Tables.Add(dt1);
//Relation object
DataRelation rel = new DataRelation("relation1", dt.Columns[0], dt1.Columns[0]);
ds.Relations.Add(rel);

bindingSource1.DataSource = ds;
bindingSource1.DataMember = "One";

bindingSource2.DataSource = bindingSource1;
bindingSource2.DataMember = "relation1";


textBox1.DataBindings.Add("Text", bindingSource1, "No");
textBox2.DataBindings.Add("Text", bindingSource1, "Name");
textBox3.DataBindings.Add("Text", bindingSource2, "No");
textBox4.DataBindings.Add("Text", bindingSource2, "Address");
}

private void button1_Click(object sender, EventArgs e)
{
bindingSource1.Position += 1;
}

private void button2_Click(object sender, EventArgs e)
{
bindingSource1.Position -= 1;
}

private void button3_Click(object sender, EventArgs e)
{
bindingSource2.Position += 1;
}

private void button4_Click(object sender, EventArgs e)
{
bindingSource2.Position -= 1;
}
...

0 comments: