How to use ADO.Net to select data from a DataTable? - c#

Using: ado.net
How can I select data from a DataTable using SQL with an aggregation function?
I know that I can use select property (http://msdn.microsoft.com/en-us/library/t5ce3dyt(vs.71).aspx ) but I need an aggregation function to use it with, and I didn't find any examples for this.

Aggregates in DataSet are normally used in conjunction with relations:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemdatadatacolumnclassexpressiontopic.asp
Basically if you need your result as single row with single column, you'd need to create that extra table with that column and add expression to it so you would get a single row:
Table1, column Number: 3 rows containing 1,2,3
Table2, column Average, expression set to "Avg(Table1.Number)": One rows containing 2
As to your particular example: "SELECT COUNT(*) FROM ", you could use row count: table.Rows.Count
You can also create DataView with particular filter and get number of rows in it to emulate more complex cases of COUNT.

Related

Datasource gridview c#

i'm new on .net, and i'm trying to make a gridview table that take data from a database (i bind data with <asp:sqldatasource selectcommand> tag) and for a specific integer value from this table column i want to display in gridview a string that is in another table and is specific for the integer.
So 2 tables, 1 is inserted in gridview, another has static number of columns, table "a" has integers and other columns, tabel "b" has same integers but different strings on other columns for them. In gridview i want to show other columns from table "a" and 1 column from table "b".
I can display the first table but i don't have ideas to link 2 tables.
I can't make changes in databes.
Thank you!
Table a Table b
column1 column2 column3 column4 column5
data1 data2 integer integer string
Output
Gridview
column1 column2 column5
To display the other data, then simply use a left join in your sql.
So, say we have this to load up the data grid:
if (IsPostBack == false)
{
GridView1.DataSource = Myrst("Select FirstName, LastName, Hotel_ID FROM tblBooked");
GridView1.DataBind();
}
We thus get this result:
But, that hotel_id is rather ugly, so we want to pull that data from tblHotels
So, you simply left join in the other table. You can write out the sql, or say lets create a view like this:
Now, our simple code can say go like this:
GridView1.DataSource = Myrst("SELECT * from vBookedHotels");
GridView1.DataBind();
And we get this result:
So the "general" approach here is to write some sql and use a left join. You can thus quite much pull in any "id" value and translate it to the other table. So friendly text names or descriptions can thus be pulled from the other table.
I recommend using SQL for this, since then your two lines of code to load up the gridview can be done as per above. And it often possible that you need to do this in several places in your application - so a handy view to query against makes is rather easy.
in above, I use a custom routine called MyRst(), and all it does is create the sqlcommand object, get the connection and returns a data table (i was tired of writing the same code over and over (eg: create connection, create data adaptor etc - so I just put that code in a simple routine, and now I can just type in some sql and quite much assign it to a gridview, or even a listview, or even dropdown boxes with the two lines of code as per above.
So, the general approach here is to use SQL to get/grab/pull and translate some "ID" in a column to some nice user friendly description or text columns in the 2nd table as you outlined.

Sqlite query multiple columns and group by them

This is my table:
I am basically using the following table to pass a select statement and viewing it as a pie graph.The pie graph excludes fields that are null or 0. So First i used the following query to select the total number by its respective group number and it worked fine. This is the working query.
query = "Select groupNumber as \"Group Number\", totalNumber as \"Total Number\" From " + table;
However i found it hard to read since both columns are numbers and therefore figured it will be better to pass a query where i can select the total numbers by its respective groupName. This is a problem though because if u look at the table you will notice that groupNames can be repeated.
Therefore i would like to do a select satement where i can query the total number by the groupnumber and groupname.
Is this possible if so how? Also i can't modify the data as i receive it in such format from a established connection.

Select count from datatable against dynamic query

I have a data set in memory which has two data tables in it.
Cont
Ins
Secondly i have separate data table (in memory) in which i have rows in following format.
And suppose it has two rows. In actual it may have million of rows
ID TableName ColumnName Operator value
1 Const ID = 1
2 Ins app_ID = 558877
As is: Now i get information from given rows and construct a query and execute it in database server like:
Select count(*) from Cont.Id= 1 and Ins.app_id = 558877;
On the basis of above query result i have implemented my business logic.
Objective: In order to increase performance i want to execute query in application server as now i have complete table in memory. how can i do it.
Note: Tables name may vary according to data.
Do you really want to keep tables with millions of rows in memory?
In terms of counting an in memory table, how is it kept? If it's a datatable as per your tag you can use the DataTable.Rows.Count property.
If your table names aren't known, you can loop over the tables in DataSet.Tables and call Rows.Count on each of them.
You have to create index on app_ID field. After that your count will run with good performance.
Your query references undefined alias "Ins". You must specify another table in FROM/JOIN clause and change "count()" to "count(Cont.)"

Natural Join of two DataTables in C#

I have a DataSet that contains two tables. One is considered to be nested in the other.. All I want is for it to not be nested and for there to be one table. .Merge() and LINQ just aren't doing the trick.
Here is a sample of what the main table would look like
student-id ID
--------------------
123456789 1
654987321 2
But each of these has multiple rows that they correspond to in the next table
ID Col1 Col2 etc.
----------------------
1 fact1 fact2
1 fact3 fact4
2 fact5 fact6
I want to combine them so they would look like this...
student-id Col1 Col2
-------------------------------
123456789 fact1 fact2
123456789 fact3 fact4
654987321 fact5 fact6
Everytime that I try the merge it doesn't work I get an error that I cant duplicate the primary key which is "ID" and since the merge is based on the primary key(i believe) I cant remove it.
I cant use LINQ because I want to make this generic so that the second table could have any number of columns and I cant get the select to work for that.
UPDATE: MY SOLUTION
I ended up cloning the second table to a new data table. Then adding a column called 'student-id' and deleting the ID column. The I looped through the rows of the Main table finding and related them to row in the second table... Combined all the data in an array and created a row in the final table.
The LINQ isn't as bad as you suggest. You can just use an anonymous type that holds two DataRows:
var result = from t1 in table1.AsEnumerable()
join t2 in table2.AsEnumerable() on (int)t1["ID"] equals (int)t2["ID"]
select new
{
Student = t1,
Facts = t2
};
foreach(var s in result)
Console.WriteLine("{0} {1} {2}", s.Student["student-id"], s.Facts["Col1"], s.Facts["Col2"]);
That way, you're not including specific columns in your output, so you can access them after the fact.
That being said, the other poster's suggestion of using a pivot table is probably a better direction to go.
let's try it in SQL.
Let, 1st Table = Table1 and 2nd Table = Table2
SQL:
Select
X.student-id,Y.Col1,Y.Col2
From Table1 As X Inner Join Table2 As Y On Y.ID=X.ID
I think if you try it in SQL it's easy to do!!!
Sounds like what you need is a Pivot table.
This will essentially allow you to display the data how you want.
Here are a couple of tutorials/projects
http://www.codeproject.com/Articles/25167/Simple-Advanced-Pivots-with-C-and-ASP-NET
http://www.codeproject.com/Articles/46486/Pivoting-DataTable-Simplified
Update
you may find yourself better doing the 'pivot' part in MS SQL as stored procedure and then populating your datatable with the results of calling this stored procedure. This example here is a great starting block
http://blogs.msdn.com/b/spike/archive/2009/03/03/pivot-tables-in-sql-server-a-simple-sample.aspx

Filter gridview data with one row

I am getting records from three tables in grid-view.
Here two table data is always the same but one table data shows different records I want to show third table data in one row in grid-view, when third table data gets the record then it needs to be filtered with comma separated using c#.
You will have to make custom datatable acoording to your need, and bind the datatable to gridview.
You can store return result in a list and filter it before bind to grid.
you need to use the union in your query to avoid the duplicate records rather than doing after binding the records.
You may get 50 records from the database but after removing the duplicates you may have just 5 to 10 records so why you want to get the 50 records, why can't remove them at the time of querying them.
Use something like this:
select x, y, z from Table1
Union
select x, y, z from Table2
Union
select x, y, z from Table3
It will always give you the ditinct records.

Categories