Print -
C# Dataset table relations
using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
string firstSql = null;
string secondSql = null;
connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
firstSql = "Your First SQL Statement Here";
secondSql = "Your Second SQL Statement Here";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(firstSql, connection);
adapter.SelectCommand = command;
adapter.Fill(ds, "Table1");
adapter.SelectCommand.CommandText = secondSql;
adapter.Fill(ds, "Table2");
adapter.Dispose();
command.Dispose();
connection.Close();
//creating data relations
DataRelation relation ;
DataColumn table1Column ;
DataColumn table2Column ;
//retrieve column
table1Column = ds.Tables["Table1"].Columns[0];
table2Column = ds.Tables["table2"].Columns[0];
//relating tables
relation = new DataRelation("relation", table1Column, table2Column);
//assign relation to dataset
ds.Relations.Add(relation);
MessageBox.Show ("Data relation completed");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}