Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

FOR LOOP NESTED QUERY FOR DATABASE 4

Status
Not open for further replies.

UKLAD1980

Programmer
Dec 6, 2008
28
GB
Hi Guys

Really sorry to trouble you all but I could really use some help on this.



I am currently learning from a book about database programming in c#. I have loaded the data into my dataset etc.


just for example data set is.....


PersonName Age

John 34

James 23

Simon 45

Peter 15


Using the above example dataset how does the following code work step-by-step in each stage.

foreach (DataRow dRow in dt.Rows)

{

foreach (DataColumn datacol in dt.Columns)

Console.WriteLine(dRow[datacol]);

Console.WriteLine("================");

}




How does the loop work in each stage?? How is a for loop different to a foreach loop?

If I can see step by step then I will be able to understand.
Any help would be amazing. Sorry If this question is very simple for you professionals. I guess we all have to start from somewhere.

As I said I would appreciate as much help as possible.

Cheers


:)
 
No problem mate. You do understand though you are now my beacon of c# hope though - time pending of course :) As I said in my message I sent you a facebook message and another message on your forum ... bit stalkerish I know :) However most importantly strictly hetro :) (people may get the wrong idea son)

Hit me up on uklad1980 @ live com if you want to, or if get the chance.

Cheers again.
 
Harley,

Quick question about the above.... sorry!!


In the loop...

foreach (DataColumn datacol in dt.Columns)

Console.WriteLine(dRow[datacol]);

Console.WriteLine("================");



.... I understand the loop carries the value of the first column and the prints out 'John' but why doesn't it then move onto the next writeline and print "=========" and then move back to the beginning of the nested column loop and then grab the value '34'? I thought that is how loops worked? Why is going to Console.WriteLine(dRow[datacol]);
then moving back up to foreach (DataColumn datacol in dt.Columns)

Hope I'm making myself clear bro.

Cheers
 
No worries, I get what you mean mate [smile]

What is happening is that if you don't include the curly braces in in your loop it is assumed that the next line is what is being looped.

For readability it might be worth always using the braces, so your statement would read:
Code:
foreach (DataColumn datacol in dt.Columns)
{
Console.WriteLine(dRow[datacol]);
}
Console.WriteLine("================");
Hope this helps

HarleyQuinn
---------------------------------
You can hang outside in the sun all day tossing a ball around, or you can sit at your computer and do something that matters. - Eric Cartman

Get the most out of Tek-Tips, read FAQ222-2244: How to get the best answers before posting.

 
Aaaaaaahhh! Makes sense now. Strange ting is it still works just as well without the curly braces as with my original post??

Sorry for bothering you mate.

Thanks.
 
oh is there a difference between a for loop and foreach loop?

Sorry for being a pain mate.
 
A for loop loops from a set numeric value to a set numeric value (set by the user)

A foreach loop (as Bob posted earlier) loops "for each element in an array or an object collection"

Hope this helps

HarleyQuinn
---------------------------------
You can hang outside in the sun all day tossing a ball around, or you can sit at your computer and do something that matters. - Eric Cartman

Get the most out of Tek-Tips, read FAQ222-2244: How to get the best answers before posting.

 
UKLAD1980 said:
but why doesn't it then move onto the next writeline and print "=========" and then move back to the beginning of the nested column loop and then grab the value '34'?

Read what HarleyQuinn wrote and look once more at the loop. Use the indentation to see the logic of the loop properly:
Code:
[COLOR=#0000ff]// Outer Loop[/color]
[COLOR=#804040][b]foreach[/b][/color] (DataRow dRow [COLOR=#804040][b]in[/b][/color] dt.Rows)
{
  [COLOR=#0000ff]// Inner Loop[/color]
  [COLOR=#804040][b]foreach[/b][/color] (DataColumn datacol [COLOR=#804040][b]in[/b][/color] dt.Columns)
    Console.WriteLine(dRow[datacol]);

  [COLOR=#0000ff]// write Separator-Line[/color]
  Console.WriteLine([COLOR=#ff00ff]"================"[/color]);
}

[COLOR=#0000ff]// Wait for an input[/color]
Console.ReadLine();
You can see, you have in your inner foreach-loop only 1 statement - i.e.
Code:
Console.WriteLine(dRow[datacol]);
So the inner foreach-loop writes all columns and then in the next step the separator will be printed.

Try to change your inner foreach-loop so:
Code:
[COLOR=#0000ff]// Outer Loop[/color]
[COLOR=#804040][b]foreach[/b][/color] (DataRow dRow [COLOR=#804040][b]in[/b][/color] dt.Rows){
  [COLOR=#0000ff]// Inner Loop[/color]
  [COLOR=#804040][b]foreach[/b][/color] (DataColumn datacol [COLOR=#804040][b]in[/b][/color] dt.Columns){  
    Console.WriteLine(dRow[datacol]);
    [COLOR=#0000ff]// write Separator-Line[/color]
    Console.WriteLine([COLOR=#ff00ff]"================"[/color]);
  }
}

[COLOR=#0000ff]// Wait for an input[/color]
Console.ReadLine();
Now the inner foreach-loop contains 2 statements:
Code:
    Console.WriteLine(dRow[datacol]);

    Console.WriteLine("================");
So in this case the separator line will be printed after each field (column).
 
Thank you chaps. I totally understand now. Thanks for your time.
 
Guys,

Really sorry about this but I have another question (maybe more dumb that the last)....

in terms of creating a table (by the book), why is it the construction is

DataTable mydatatable = mydataset.Tables["Customers"];


Could we not use ....

DataTable mydatatable = new DataTable();

mydatatable = mydataset.tbale["Customers"];

Would I not be missing any properties and methods this way?

Sorry again.

instead of
 
Code:
DataTable mydatatable = mydataset.table["Customers"];
Code:
DataTable mydatatable = new DataTable();
mydatatable = mydataset.table["Customers"];
for all practical purposes, this is the same code. however there are technical differences.

in the second block of code you have 2 datatables. the new MyDataTable() in line 1 and the data table returned in line 2. the datatable from the dataset will replace the instiantiated datatable from line one.

at a micro-scale the second block of code requires more system resources/memory. however the difference is so minute, it's not worth mentioning other than an academic reason.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Hi Jason,

I do not understand - sorry. In the second block of code I have created a new Datatable called myDataTable. Then I have gave it a value by assigning mydataset.table["Customers"]..... or have I got that wrong?

Isn't the first line of code just referencing the object but not holding any value as we haven't used the 'new' keyword?

Thanks
 
mydataset.tables["Customers"] returns a reference to a datatable containing customers. the instantiation of the datatable is managed by the dataset.

one concept in programming is to limit the instantiation of concrete implementations. this is done in a variety of ways.
1. IoC containers 2. Factory objects 3. program to interfaces (contracts), not implementations.

So in this instance the DataSet is acting as a factory (very loose interpretation of the pattern) by being the object that creates our datatable of customers. Another way to say it; the DataSet encapsulates the creation of the datatable.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
UK, Looking at some of your line of questioning, I think this might be helpful. What happens when you create an object is that you allocate the required space for it (in an area of memory called the "heap"), and then give the variable a "reference value" (actually a long integer) which refers to the allocated space. So, if you set your object variable equal to an existing object, you just set it equal to an existing reference value. If you use the new keyword, you create a new reference value.

This means that if you create a new reference value, allocate new memory on the heap, then set your variable equal to an existing reference value, all you're doing is allocating memory that you don't use and then deallocating it again.

Now, these two code statements are equivalent:

Code:
DataTable mydatatable;  //omitting "= new DataTable;"
mydatatable = mydataset.table["Customers"];

Code:
DataTable mydatatable = mydataset.table["Customers"];

If you use the new keyword in the first line, they are NOT equivalent as I have explained. However, the end result is the same in all cases: you have an object that references an existing DataTable in the DataSet object.
 
UK, if you click on Harley's and my names here, you will see that between us we have about 3500 posts in the VB6 forum, as well as quite a few in other places. So we go back a ways. :)

Also, there isn't exactly a "pure C#" and a "database C#". Every .Net language uses the same database objects, such as the two that you have been working with here. So, to refine your distinction, I would suggest that you have "C#" and the ".Net framework." C# is a means of creating and using the libraries of objects in the .Net framework. You can use any language in Visual Studio to access the .Net framework, so most programs can be just as easily written in VB.Net or C++ as C#. They would all access the same objects, you see, and some of those would be the database objects in "ADO.Net."
 
Thanks Bob. That makes a lot of sense. Think my problem is I'm trying to learn to much and getting very frustrated as I usually (well like t think) I pick things up fairly quickly. I was ready to throw the towel in but fater reading your post, maybe it is not to bad and everyone has to start somewhere.
 
I was ready to throw the towel in but fater reading your post, maybe it is not to bad and everyone has to start somewhere.
exactly. we all started somewhere, and we all can learn something new each day. Trying to master all this at once is like drinking form a fire hose.

You can use any language in Visual Studio to access the .Net framework, so most programs can be just as easily written in VB.Net or C++ as C#.
to expand on Bob's list of languages. the big 2 .net languages are C#, VB. C++ is a distant second, and then you get into the misc. languages. J++, Python, Ruby, Boo. these all work with the .net framework as well, they are just not as common, and require additional references so the interpreter can translate the langauge to IL. this is all transparent to a majority of developers because they are using either VB or C# with Visual Studio.

And because it is all compiled into IL (which I cannot remember what that stands for) you can mix and match languages in projects. Your web GUI could be written using Ruby, the Core domain C#. and maybe a few windows services utilize Boo or Python. But I wouldn't recommend this.

One issue I have with how MS promotes the .net framework and VS is by making an implicit statement that anyone can write a program in 5 minutes using VS. And yes this is true, because you don't actually have to write an code. between drag/drop controls and Wizard driven configurations you can get a form/website up and running with minimal effort. But that's where it stops for alot of devs. Concepts like refactoring for readability and maintainability, unit testing, separation of concerns, design principles like SOLID and common design pattern aren't mentioned and developers don't realize the full potential of OOP.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Thank you Jason. It does put a lot into perspective.

Until about a month ago I was a Business Analyst contractor working within Government. For me it wasn't about the daily/hourly rate but the day-to-day duty and achievements. It started to get a bit repetitive and boring so I literally jut ended my contract and decided to take a new direction.

In many ways you guys may think I am mad, or even selfish given the current economic climate but my job wasn't doing it for me.

So, I have decided to go into development. I was thinking along the lines of C# , ASP and Sharepoint. I have a lot of great books. Funnily enough I have got two computing degrees (yep they aren't worth much nowaday's) so I like to think the learning process won't be too difficult. However, It would be nice to know in what direction to go with the technologies - obviously as Jason said, you can't know it all but the age old question, "How much do you need to know" still plays on my mind. Yes a silly question asked by many no doubt.

I would like to say you guys have been a really good source of help. I have never used forums for guidance before but they have opened my eyes to a new world :)
 
Until about a month ago I was a Business Analyst contractor working within Government. For me it wasn't about the daily/hourly rate but the day-to-day duty and achievements. It started to get a bit repetitive and boring so I literally jut ended my contract and decided to take a new direction.

In many ways you guys may think I am mad, or even selfish given the current economic climate but my job wasn't doing it for me.
there is nothing selfish about pursing interests that you are passionate about. Nothing in more draining on a person than meaningless work.

as your journey takes shape I would encourage you to check out 1. Agile development practices and 2. the alt.net community. There are also alot of great OSS projects in the .net community which can increase productivity of your code.

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Ok mate. Thank you I will have a look at Agile. I have a fairly good design patterns resource to. Could one of you chaps give me some advice on the following data bind? The code seems to compile but yet the DataGrid remains grey. Any ideas?

Cheers



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace MultiTableDataGrid
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
// create connection string

string connec = @" Server=localhost\SQLEXPRESS; Integrated Security=true; database=Northwind";

// query string


string SQL = " SELECT * FROM Employees;" + " SELECT * FROM Orders;";

// create connection object

SqlConnection sqlconnec = new SqlConnection(connec);

// create new datadapter object

SqlDataAdapter mydataadapter = new SqlDataAdapter(SQL, connec);

mydataadapter.TableMappings.Add("Table", "Employees");
mydataadapter.TableMappings.Add("Table1", "Orders");

// fill DataSet using the adapter

mydataadapter.Fill(dataSet1);


/* Create a relationship between the two tables
* and add it to the dataset1*/

DataRelation mydatarelation = new DataRelation("EmployeeOrders", dataSet1.Tables[0].Columns["EmployeeID"], dataSet1.Tables[1].Columns["EmployeeID"]);

dataSet1.Relations.Add(mydatarelation);

// bind the data at run time

dataGridView1.DataSource = dataSet1;

}
}
}
 
not sure about WinForms, but with WebForms you would need
Code:
dataGridView1.DataSource = get_data();
dataGridView1.DataBind();

Jason Meckley
Programmer
Specialty Bakers, Inc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top