DataRelation class is very useful class. It is used to connect tables without using sql query. We can get the data of the table separately by using the class DataRelation we can join those tables and get result. The following code will expalain it clearly. Name space part
using System; using System.Data; using System.Data.SqlClient; using System.Collections.Generic; using System.Text;
Code Part
SqlConnection MySqlConnection = new SqlConnection("Connection String"); DataSet MyDataSet = new DataSet();
SqlDataAdapter DeptAdapter = new SqlDataAdapter( "SELECT * FROM Department", MySqlConnection); SqlDataAdapter EmpAdapter = new SqlDataAdapter( "SELECT * FROM Emp", MySqlConnection); DeptAdapter.Fill(MyDataSet, "Department"); EmpAdapter.Fill(MyDataSet, "Emp");
DataRelation MyDataRelation = MyDataSet.Relations.Add("DeptEmp", MyDataSet.Tables["Department"].Columns["Deptid"], MyDataSet.Tables["Emp"].Columns["Deptid"]);
foreach (DataRow DeptRow in MyDataSet.Tables["Department"].Rows) {
Console.WriteLine(DeptRow["DepartmentName"]); foreach (DataRow EmpRow in DeptRow.GetChildRows(MyDataRelation)) { Console.WriteLine(EmpRow["EmpName"]); } } MySqlConnection.Close();
Code Explanation
1. Create SQL Connection 2. Create Dataset 3. Create two SqlDataAdapter for Department and Emp tables 4. Fill the data into the SqlDataAdapters 5. Create the relation between the two tables by common id Deptid using the DataRelation class. 6. using for loops we can get Departmentwise Emp name as shown in the above code
By Nathan
|
No responses found. Be the first to respond and make money from revenue sharing program.
|