Return multiple values from a SELECT query
c#, sql
Solution
This should give you a list of strings that you want in the fastest manner. `reader.GetString(0)` means that you take a sting value from column with index 0 (so the first one).
List<string> result = new List<string>();
using (SqlConnection connection = new SqlConnection(databaseConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
result.Add(reader.GetString(0));
}
reader.Close();
}
command.Cancel();
}
}
return result;
Problem
For example i have a database called dbuser: ``` username: teste password: xxxx isonline: 1 username: teste2 password: xxxx isonline: 1 ``` I thought that this query: ``` "SELECT username FROM dbuser WHERE (isonline ='1')" ``` would return both teste and teste2, but when i ask the result for example in a MessageBox, with both teste and teste2 online, it only shows teste, but when i close the teste connection then it appears teste2 in the MessageBox. Im guessing its only returning the first row to me, so how can i get all the values? This is the method code: ``` public static string GetOnline() { string listaOnline; listaOnline = ExecuteQuery("SELECT * username FROM dbuser WHERE (isonline ='1')").ToString(); return listaOnline; } ``` and I show it as `MessageBox.Show(DbManager.GetOnline());`