Loading DataTable with multiple tables select query - c#

I never used select queries with multiple tables involved before and now when I do, I'm having troubles with getting the information from the DataTable.
I have this query:
SELECT *
FROM [Usergroups], [Groups]
WHERE [Usergroups.UserID] = #name
AND [Groups.GroupID] = [Usergroups.GroupID]
And this is how I get the returned values into a DataTable:
DataTable groupsTable = new DataTable();
groupsTable.Load(sqlCmd.ExecuteReader());
Now, how can I specify my DataTable from which table I want to take rows from? For example, this is what I did before multiple tables where involved:
string groupName = groupsTable.Rows[0]["Name"];
I could not find any resource with such information, but I know it's a basic question. Thanks in advance.

The query in your question doesn't produce, as a result, multiple tables.
It produces a JOIN between two tables.
As a consequence, on the C# side, you don't have two tables but just one as before, with the all fields from both tables.
As a side note, a better way to JOIN tables together is through the use of the JOIN statement like this
SELECT * -- a field list is better here ---
FROM Usergroups ug INNER JOIN Groups g ON g.GroupID=ug.GroupID
WHERE ug.UserID=#name
and you should add, to the SELECT clause, a list of the fields that you are really interested in.
SEE a simple JOIN reference
If you want to retrieve the values of the two tables in separate DataTable objects, then you need to use a DataSet in this way
DataSet ds = new DataSet();
DataTable dtUserGroups = new DataTable("UserGroups");
DataTable dtGroups = new DataTable("Groups");
ds.Tables.Add(dtUserGroups );
ds.Tables.Add(dtGroups);
using(SqlCommand cmd = new SqlCommand("SELECT * FROM UserGroups;SELECT * from Groups", con))
{
using(SqlDataReader dr = cmd.ExecuteReader())
{
ds.Load(dr, LoadOption.OverwriteChanges, dtUserGroups, dtGroups);
// Now you have the two tables filled and
// you can read from them in the usual way
}
}
This last example could further enhanced adding a DataRelation object to the DataSet to represent the relationship between the two tables. This could allow your code to navigate the parent/child recordset.

You may try in this way :
string query = "SELECT U.ID,U.NAME, C.NAME AS CUSTOMERNAME, C.DOB FROM USER U INNER JOIN CUSTOMER C ON U.ID = C.USERID"
SqlConnection conn = new SqlConnection(_connectionString);
SqlCommand cmd = new SqlCommand(query, conn);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
Above code will return you one DataTable with data from two different tables say "User" and "Customer".
I hope now you know how to access data from a DataTable.

It is better to use JOIN for combining multiple tables such as INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL JOIN as per your requirements. So, when you use INNER JOIN, it will have the columns of two joined tables, i.e., if
tblA has a, b,c as columns and
tblB has a, e,f as columns
then the inner joined table will have a, b, c, e, f as its columns.
Then, you can use like this:
public DataTable LoadData()
{
DataTable dataTable;
string connString = #"your connection string here";
string query = "SELECT * FROM Usergroups t1 INNER JOIN Groups t2 ON t2.GroupID=t1.GroupID WHERE t1.UserID=#name";
SqlConnection conn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(query, conn);
conn.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dataTable);
conn.Close();
return dataTable;
}
After Getting the DataTable, then you can use this table like:
DataTable dt = LoadDataClass.LoadData();
string groupName = dt.Rows[0]["Name"]; //For first row
I hope you get it.

in wpf c#, this method can also be used to retrieve data from multiple tables
try
{
using (SqlConnection conn = new SqlConnection(_pageDataBase.connectionString()))
{
conn.Open();
DataTable dt = new DataTable();
SqlDataAdapter Usergroups= new SqlDataAdapter("select *from Usergroups", conn);
Usergroups.Fill(dt);
SqlDataAdapter Groups= new SqlDataAdapter("select *from Groups", conn);
Groups.Fill(dt);
datagridName.ItemsSource = dt.DefaultView;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Related

C# Aggregate argument

In C#, I would like to run the below query on Access
query = #"SELECT Jobs.Client, Jobs.Name, Jobs.Area,
Jobs.DevHours, Sum([Activities.Duration]) AS SumOfDuration
FROM Jobs INNER JOIN Activities ON Jobs.ID = Activities.JobId
GROUP BY Jobs.Client, Jobs.Name, Jobs.Area, Jobs.DevHours;";`
After making the query, I am using a dataadapter to read and fill the data into a datatable:
OleDbCommand command = new OleDbCommand
{
CommandText = query,
Connection = connection
};
OleDbDataAdapter da = new OleDbDataAdapter(command);
DataTable table = new DataTable();
da.Fill(table);
however in run-time I face an error, which is saying
Cannot have Memo, OLE, or Hyperlink Object fields in aggregate argument ([Activities.Duration])
I really appreciate if someone can help me.

Populating Datagrid with Data from Multiple Tables

I need to populate a datagrid with the following columns.
invnumber,itemname,rate,quantity..
itemname,rate,quantity comes from 1 table while invnumber comes from another table
I used to do like this
string commandText = "SELECT invnumber,cname,date FROM inv_table WHERE invnumber LIKE #id";
SqlCommand command = new SqlCommand(commandText, conn);
string searchParam = String.Format("%{0}%", text_inv.Text);
command.Parameters.AddWithValue("#id", searchParam);
using (SqlDataAdapter sda = new SqlDataAdapter(command))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
dataGridView2.DataSource = dt;
}
}
Now i cannot directly assign the data source as 2 different tables are involved
dataGridView2.DataSource = dt;
How can i get around this.
To emit combined result from 2 or more different tables in a table, use either INNER JOIN, LEFT JOIN, RIGHT JOIN or UNION statement depending on your need.
In this case, you need to join first table and other table to get desired results, assume invnumber is unique or primary key. Here is an example:
string commandText = "SELECT other.invnumber, inv.cname, inv.date FROM inv_table AS inv
INNER JOIN other_table AS other
ON inv.invnumber = other.invnumber
WHERE other.invnumber LIKE #id";
Or if you have already defined classes for each table, use LINQ to SQL with lambda expression:
DataContext dc = new DataContext();
var results = dc.InvTable.Join(OtherTable, inv => inv.invnumber, other => other.invnumber, (inv, other) => new { invnumber = other.invnumber, cname = inv.cname, date = inv.date });
Any improvements and suggestions welcome.
Create a new class for the data structure of the 2 different table, populate the new one and use. (easier and the most clear solution)

merging two datasets and display in one gridview

I have two seperate databases from which I want to retrieve data and display in one grid view. The difficult I have is that I have a product key only in the table from the one database and the same set of product keys agains the actual products products in the other database and now I want to display the product data in one grid view....if this makes sense.
How can I do this, merge the data and display the product data agains the keys in the one grid.
string connString = "Data Source=.\\SQLEXPRESS;Initial Catalog=LRVWebsite;user ID=sa;password=lrmg;";
SqlConnection sqlCon;
OleDbConnection conn;
DataSet setOleDb;
DataSet dsSql;
private void bindData()
{
try
{
conn = new OleDbConnection(#"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();
setOleDb = new DataSet();
OleDbDataAdapter dbaOle = new OleDbDataAdapter("SELECT * FROM tblProducts", conn);
dbaOle.Fill(setOleDb);
sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(#"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
//#"SELECT C.CustomerFirstName,C.CustomerLastName,C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql);
dsSql.Merge(setOleDb);
GridView1.DataSource = dsSql;
GridView1.DataBind();
sqlCon.Close();
This is what I have tried.Now, how can I get the product key to correlate with the actual product in the other table which contains the same product key?
I think this is a commonly faced scenario. Here is a detailed link from msdn.
Merge Data Set Contents
As much as I understand, you have 2 tables in one database and one table in the other database and you are wanting to combine all of these data set and display it as one.
If I am correct then you can do joins across the databases;
select * from dbo.firstdatabasetable db1
inner join apple.primarykeys db2
on db2.primary = db1.primary
inner join orange.seconddatabase db3
on db2.productname = db3.productname
If databases are hosted on different Machines across the network then you can find the DB servers with select sys.servers
Lets say the the first server is x and the second one is y
then;
select * from x.dbo.firstdatabasetable db1
inner join x.dbo.primarykeys db2
on db2.primary = db1.primary
inner join y.dbo.seconddatabase db3
on db2.productname = db3.productname
inner join x.dbo.primarykeys

how to join two datatable datas into one datatable to show in one gridview in asp.net

how to join two datatable datas into one datatable to show in one gridview
i.e in 1 datatable i have username and pwd and in another datatable i have that user details. how to show all these in one datatable to get those values display in gridview(asp.net)
any idea????
on=new SqlConnection("Data Source=MCN101; Initial Catalog=MergeTable; Uid=sa; pwd=");
da = new SqlDataAdapter("Select * from Table1", con);
da.Fill(ds1, "Record");
da = new SqlDataAdapter("select * from Table2", con);
da.Fill(ds2, "Record");
ds1.Merge(ds2);
GridAllRecord.DataSource = ds1;
GridAllRecord.DataBind();
You can merge two datatable, here is the sample for that.
http://msdn.microsoft.com/en-us/library/system.data.datatable.merge.aspx
What you need is a join on the tables before reading them into a DataTable: SQL Joins
#Ranjana have a look at this MSDN article it deals with what you want..

Define table names for results of multiple SQL selects in a single query

For example if I run the following query:
select * from table1
select * from table2
And run it with a DB adapter (C#) I get a dataset with two tables.
How can I define the names for the result tables in SQL?
I can only do this inside the SQL. I don't have access to the c# code.
#Timothy Khouri: It can be done! EDIT: but not at the SQL level!
You can use TableMappings on the DataAdapter.
If the SelectCommand of a DataAdapter returns multiple result sets, the DataAdapter uses table mappings to fill corresponding DataTables in a DataSet. By default, the first result set will be filled to a DataTable named "Table", and the second result set will be filled to a DataTable named "Table1" etc.
SqlDataAdapter sqlDa = new SqlDataAdapter();
SqlCommand selectCmd = new SqlCommand();
selectCmd.CommandText = "spReturnMultpileResultSets";
selectCmd.CommandType = CommandType.StoredProcedure;
selectCmd.Connection = this.sqlConnection1;
sqlDa.SelectCommand = selectCmd;
// Add table mappings to the SqlDataAdapter
sqlDa.TableMappings.Add("Table", "Customers");
sqlDa.TableMappings.Add("Table1", "Orders");
// DataSet1 is a strongly typed DataSet
DataSet1 ds = new DataSet1();
this.sqlConnection1.Open();
sqlDa.Fill(ds);
this.sqlConnection1.Close();
Refs:
http://blogs.msdn.com/vsdata/archive/2007/03/08/tableadapter-multiple-result-sets.aspx
http://www.eggheadcafe.com/software/aspnet/32696845/strongly-typed-datasets.aspx

Categories