0

I was using this piece of code until i realized it only returns one piece of information. What is the correct method to use to retrieve multiple items?

sqlconn.Open();
SqlCommand cmd = new SqlCommand("Select [Description] from [dbo].[Categories] ", sqlconn);
string result = (string)cmd.ExecuteScalar();
Console.WriteLine(result);
sqlconn.Close();

I have this ready to take a part an Array i just cant find out how to get it to return an array.

foreach (var item in result)
{
    Console.WriteLine(item);
}
4
  • 1
    you are saving your result to a string, save your result to a list so you can loop through the results. use var result Commented Jan 7, 2019 at 19:15
  • That fixes the second problem but the main issue is ExecuteScalar() returns back only one item. I'm wondering is there a different function i could call anyone is aware of? Commented Jan 7, 2019 at 19:20
  • 2
    There are many ways. Look into ExecuteReader() first. Commented Jan 7, 2019 at 19:23
  • Thanks just figured it there , couldn't get it earlier for some reason thanks for the help though Commented Jan 7, 2019 at 19:26

1 Answer 1

4

ExecuteReader will return multiple items but you need to use a while loop to break down the results.

sqlconn.Open();
SqlCommand cmd = new SqlCommand("Select [Description] from [dbo].[Categories] ", sqlconn);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
      Console.WriteLine(reader[0]);
}
Sign up to request clarification or add additional context in comments.

2 Comments

No need for String.Format here. You can simply use: Console.WriteLine(reader[0]);
Very true, just had it left in from what i was doing , Edited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.