C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Code Snippets » ADO.NET »

Data Relation in Sql using C#


Posted Date: 27 Oct 2009    Resource Type: Code Snippets    Category: ADO.NET
Author: Shunmuganathan MMember Level: Diamond    
Rating: 1 out of 5Points: 10



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




Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Data Relation  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Get the table details
Previous Resource: Sqlexceptionclasses
Return to Discussion Resource Index
Post New Resource
Category: ADO.NET


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use