473,765 Members | 1,940 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question on DataTable join

Hi, I have two datatables and I want to efficiently query the
intersection of the two using the studentID. In my example code below,
I want to print out Mary and Jane and their exam grades and I don't
want to use loop because the real datatables are much larger. Can this
be done using one of the inbuilt methods in the class library and if
so how.
Thank you in advance
Peter

DataTable examgrade;
DataTable students;

private void addExamgrade(in t studentID, string grade)
{
DataRow dr=examgrade.Ne wRow();
dr["STUDENTID"]=studentID;
dr["GRADE"]=grade;
}

private void addstudent(int studentID, string studentname,int
yearenrolled)
{
DataRow dr=students.New Row();
dr["STUDENTID"]=studentID;
dr["STUDENTNAM E"]=studentname;
dr["YEARENROLL ED"]=yearenrolled;
}

private void button1_Click(o bject sender, System.EventArg s e)
{
examgrade=new DataTable();
examgrade.Colum ns.Add("STUDENT ID",typeof(int) );
examgrade.Colum ns.Add("GRADE", typeof(string)) ;
addExamgrade(10 1,"A");
addExamgrade(10 2,"B-");
addExamgrade(50 0,"C");
addExamgrade(15 0,"FAIL");

students=new DataTable();
students.Column s.Add("STUDENTI D",typeof(int)) ;
students.Column s.Add("STUDENTN AME",typeof(str ing));
students.Column s.Add("YEARENRO LLED",typeof(in t));
addstudent(400, "Fred",1982 );
addstudent(300, "John",1975 );
addstudent(100, "Mark",2003 );
addstudent(500, "Mary",1960 );
addstudent(150, "Jane",2002 );

//hardcoded answer
Console.WriteLi ne("The students and their grades are");
Console.WriteLi ne("Mary C");
Console.WriteLi ne("Jane FAIL");
}
Nov 16 '05 #1
3 9258
hi
you can use the Find and Select method of the databale object.
these are two built in function of the datatable object . the select
method is rather simple .it takes as input a string "SQL query" and return
an array of dataraws
DataRow[] result = tableName.Selec t("name = 'whatever' ");
the find method returns only one datarow , this is because it search with
the primary key of the table . therefore, to use this method you need to
define a primary key to the table you are searching into . to define a
primary key set the PrimaryKey property of the datatable to an ARRAY of
datacoumns
mytable.Primary Key = new DataColumn[]{mytable.Column s["index or
name of the primary key column"].
then you can use find to get the row that has this specific value " the one
you are looking for " on its primary key feild
DataRow result = mytable.Find("s ome value for the primary key");

hope that was clear , if not you can read more about these two methods on
the msdn online or you can post your inquries .
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC

Nov 16 '05 #2
Hi there - yes this is clear.

But my friends at school are talking about creating a "DataRelati on"
and just doing one query. I don't understand how I can do ONE query on
a "DataSet" containing two tables.

Here is my modified code (another whole day writing this small code).
Thank you again
Peter

private void button1_Click(o bject sender, System.EventArg s e)
{
examgrade=new DataTable();
examgrade.Colum ns.Add("STUDENT ID",typeof(int) );
examgrade.Colum ns.Add("GRADE", typeof(string)) ;
addExamgrade(10 1,"A");
addExamgrade(10 2,"B-");
addExamgrade(50 0,"C");
addExamgrade(15 0,"FAIL");

students=new DataTable();
students.Column s.Add("STUDENTI D",typeof(int)) ;
students.Column s.Add("STUDENTN AME",typeof(str ing));
students.Column s.Add("YEARENRO LLED",typeof(in t));
addstudent(400, "Fred",1982 );
addstudent(300, "John",1975 );
addstudent(100, "Mark",2003 );
addstudent(500, "Mary",1960 );
addstudent(150, "Jane",2002 );

DataSet ds=new DataSet();
ds.Tables.Add(e xamgrade);
ds.Tables.Add(s tudents);

DataColumn dcParentStudent ID=ds.Tables[0].Columns["STUDENTID"];
DataColumn dcParentGrade=d s.Tables[0].Columns["GRADE"];

DataColumn dcChildStudentI D=ds.Tables[1].Columns["STUDENTID"];
DataColumn dcChildStudentN ame=ds.Tables[1].Columns["STUDENTNAM E"];
DataColumn dcChildYearEnro lled=ds.Tables[1].Columns["YEARENROLL ED"];

DataRelation dr=new DataRelation("j oin",new
DataColumn[]{dcParentStuden tID},new
DataColumn[]{dcChildStudent ID},false);
ds.Relations.Ad d(dr);

//Now what?
//how to I query the "ds" to get only
//Mary & Jane and C and FAIL in a textbox or dropdownlists
}
mo************@ egdsc.microsoft .com (Mohamoss) wrote in message
news:<xH******* ******@cpmsftng xa10.phx.gbl>.. .
hi
you can use the Find and Select method of the databale object.
these are two built in function of the datatable object . the select
method is rather simple .it takes as input a string "SQL query" and return
an array of dataraws
DataRow[] result = tableName.Selec t("name = 'whatever' ");
the find method returns only one datarow , this is because it search with
the primary key of the table . therefore, to use this method you need to
define a primary key to the table you are searching into . to define a
primary key set the PrimaryKey property of the datatable to an ARRAY of
datacoumns
mytable.Primary Key = new DataColumn[]{mytable.Column s["index or
name of the primary key column"].
then you can use find to get the row that has this specific value " the one
you are looking for " on its primary key feild
DataRow result = mytable.Find("s ome value for the primary key");

hope that was clear , if not you can read more about these two methods on
the msdn online or you can post your inquries .
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC

Nov 16 '05 #3
hi
using datarelation would be useful when you have a parent and child
realtion . like You can have a data relation between two tables that has a
primary key and foreign key relation. When you have that you can create a
date relation between the tables. And use the get child rows function
(offered when you use dataRelation object ) then you pass this function .
a value of the primary key of the first table . and it return all the rows
that has this value as a foreign key in the second table . So this can be
more compact in many cases ( if you have a situation like that ) .. hope
that helps
Mohamed Mahfouz
MEA Developer Support Center
ITworx on behalf of Microsoft EMEA GTSC

Nov 16 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1567
by: gro.asumsa | last post by:
I have two DataTables in a DataSet. I would like to create a third DataTable in the same DataSet that is a Join of the two original DataTables. The two tables are extracted from two different database on two seperate servers, so doing it at time of creation is not an option. How do you create a third DataTable in a DataSet that is a Join of the two Previous DataTables Please reverse the email address when responding
2
8107
by: Ev | last post by:
I have a database table in SQL Server that has a self join. In C# I have a DataTable with a self-join. I have defined a foreign key constraint on the DataTable for the self join. The AcceptRejectRule is set to Cascade Table Structure: OrderID (Identity field) OrderDesc OrderParent (this is the self-join - it is a foreign key to OrderID) In my code I add several rows to the table, createing a hierarchy of orders
7
1712
by: Chris | last post by:
I'm using ASP.NET and SQL Server and this might be an obviuos question for most, but if I have a table that contains several fields that I need to relate to just one field in another table, how do I do that? I.e. Table 1 has Integer values for enteredbyID, CoordID, CustContactID Table 2 is the contacts table with Contact_ID (integer) key. Table 1 uses that field to bring back First and Last Name's. So: Table1 Table 2
1
2022
by: cindy | last post by:
Get data into datatable, add to dataset dsSearch " Get data into datatable, add to dataset dsSearch Using In-Memory SQL Engine join the tables and select the filenames from the join, add to dataset dsSearch CODE ON http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=3994&lngWId=10 using SQL connection get data from view on sql server, add to dataset dsSearch
1
1024
by: RJN | last post by:
Hi Need a help on data set. I have a .csv file as an input which I read using the oledb provider and upload into a dataset using a dataadapter. So the dataset has one datatable now. Using this datatable as the basis, I need to get the other related information from SQL server database. The exact scenario is like this. Suppose instead of creating a datatable if I create a temp table in SQL server, then I can join this temp table
2
40061
by: Marcel Hug | last post by:
Hi NG! With a Inner-Join SQL I get my datas in a DataSet. In the table are the column Entry and Version. Like this: Entry Version 1 1 1 2 1 3
9
1516
by: SMALLp | last post by:
Hy! I have error something like this TypeError: unbound method insert() must be called with insertData instance as first argument (got str instance instead) CODE: File1.py sql.insertData.insert("files", data)
1
11192
by: szwejk | last post by:
Hi! How to get result od dataTable from Linq query? I have typied DataSet and I want to join couple of tables. And I have a problem with change this result to DataTable type. (I don't want to rewrite everything in foreach) e.g. How can I make DataTable from it? Thx for help! var query =
0
2878
by: =?Utf-8?B?cm9uZSBtYXRpYXM=?= | last post by:
I have the same task to do but everytime I tried to parse my code I get a null value returned after executing "dtMaterials.WriteXml(swMaterials);". I am using the following code: Hope you can hep me out with this. Thanks. DataTable dtMaterials = new DataTable(); StringWriter swMaterials = new StringWriter(); swMaterials = null; string strMaterials = string.Empty;
0
9566
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10153
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9946
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8830
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6646
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5413
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3530
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2800
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.