I want select multiple (all) values from table Account.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
reader.Read();
label1.Text = reader["PasswordHash"].ToString();
connection.Close();
Why is this always returning only the first row. Actually it return one row, because if I set in where clause something like where id = 2 and id = 3
it still returns only one value.
Table have more than one value i checked form Management Studio, there query run as they should.
Thanks in advance.
Because you are not looping through the query results, it shows up only one result.
string query = "SELECT * FROM Account";
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlDataReader reader;
connection.Open();
reader = command.ExecuteReader();
While(reader.Read())
{
label1.Text += " " +reader["PasswordHash"].ToString();
}
connection.Close();
The above code loops through the query results and will give you what you want in a concatenated string assigned to label1.text
. You can also view the results by inserting Console.WriteLine(reader["PasswordHash"].ToString());
in the while
loop
You should do
while (reader.Read())
// process information
You need to iterate all the information you retrieved.
Sidenote: Use using statements on your SqlConnection, SqlCommand, and SqlDataReader to make sure the objects get disposed correctly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With