I want to turn the results of a SQL query into a C# list. I've tried using the following code which doesn't work - Visual Studio returns
An unhandled exception of type 'System.InvalidCastException' occurred in System.Data.dll
Code:
public List<string> carList(int id)
{
List<string> list = new List<string>();
SqlConnection conn = new SqlConnection(connStr);
conn.Open();
string query = "SELECT ID FROM Cars WHERE custID = " + id;
SqlCommand cmd = new SqlCommand(query, conn);
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(reader.GetString(0));
}
}
conn.Close();
return list;
}
The result of the SQL query should just be a single column with one or more ID's (integers). I then want to put these all into a list. Hopefully this gives you a bit of an idea of what I'm trying to do.
If someone could point out what I'm doing wrong here then I'd be very thankful.