Reputation: 301
Is there a way to index the reader variable so I can access every single user that's being selected? As this only gets the first record everytime
using (SqlCommand cmd = new SqlCommand("Select * from users", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
user = new Users(reader["name"].ToString(), reader["image_path"].ToString());
//MessageBox.Show(reader[1].ToString() + " " + reader[2].ToString());
}
}
}
}
Upvotes: 0
Views: 612
Reputation: 792
I think you're misinterpreting the purpose of SqlDataReader.
Each loop through
while (reader.Read())
will iterate through a row of the returned dataset. If you wish to show each user in a message box, your code ought to look something like the following.
using (SqlCommand cmd = new SqlCommand("Select * from users", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
user = new Users(reader["name"].ToString(), reader["image_path"].ToString());
MessageBox.Show(user.ToString());
}
}
}
If you wanted to show all the users joined together at the end, you'd want to do something like the following.
var users = new List<Users>();
using (SqlCommand cmd = new SqlCommand("Select * from users", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
user = new Users(reader["name"].ToString(), reader["image_path"].ToString());
users.Add(user);
}
}
}
MessageBox.Show(string.Join(" ", users.Select(x => x.ToString()));
Upvotes: 3