Reputation: 59
If I'm using a parameterized query (ASP.NET with C#) in SQL, such as
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = @pageID");
cmd.Parameters.AddWithValue("@pageID", 1);
And later on in the page, I want to do a foreach loop of whatever data was retrieved:
foreach(var row in ???)
What would I use (in place of the ???) to access the data I just retrieved?
Thanks.
Upvotes: 1
Views: 83
Reputation: 62276
It depends on how you execute a query.
Usually it's done by SqlCommand.ExecuteReader
For example, in your case, you can:
....
SqlDataReader reader = cmd .ExecuteReader();
while (reader.Read())
{
...
}
But there are also other ways to rertieve the data, for example using DataSet For a complete example on how to do that can have a look on:
Upvotes: 3
Reputation: 98810
You can use while
iteration statement with SqlCommand.ExecuteReader
instead of foreach
. Take a look this;
var db = Database.Open("Database1");
SqlCommand cmd = new SqlCommand("SELECT * FROM pageinfo WHERE pageID = @pageID");
cmd.Parameters.AddWithValue("@pageID", 1);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader[0]);
}
reader[0]
returns first row of first column and reader[1]
returns first row of second column if your data has of course.
Upvotes: 0