Вопрос

After querying for data from a database I used the datareader to fill an array. as the following.

connection.Open();
System.Data.SqlClient.SqlDataReader reader = command.ExecuteReader();
reader.Read();

_firstname = reader[0].ToString();
_Year = reader[1].ToString();
_coursename = reader[2].ToString();
_credits = reader[3].ToString();
_mark = reader[4].ToString();
_firstname2 = reader[5].ToString();

reader.Close();

I But the result show as below

1 - Sam Bons 
2- 2012 
3- DDD 
4- 3 
5- 80 

How can I perform a loop to get all the results from the DB and print it out ?

thank you


I did it as so Thank you Ann

result = string.Empty;
                int counter = 1;
                while (reader.Read())
                {
                    _firstname = reader[0].ToString();
                    _Year = reader[1].ToString();
                    _coursename = reader[2].ToString();
                    _credits = reader[3].ToString();
                    _mark = reader[4].ToString();

                    result += string.Format("{5} - {0}{1}{2}{3}{4} </br>  ",
                        _firstname,
                        _Year,
                        _coursename,
                        _credits,
                        _mark,
                        counter);
                    counter++;

                }
                Response.Write(result);

                reader.Close();
Это было полезно?

Решение

First off, you're not actually putting anything in an array, as you stated. You're just setting what look to be local variables.

If your question is about the syntax of a loop, it would be like this:

while(reader.Read())
{
   // set your variables
   // do something with the variables
}

Put that between your ExecuteReader call and your reader.Close() call.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top