0

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.

12
  • 1
    "doesn't work" - how? Do you get an error? The list is empty? Something else? Commented Jan 20, 2017 at 16:43
  • 1
    You should get the value as integer instead of GetString(0) and then call .ToString() on the value to add it in the list. Commented Jan 20, 2017 at 16:48
  • 2
    What's the data type of Cars.ID? I bet it's not a string. Try reader.GetInt32(0).ToString() Commented Jan 20, 2017 at 16:48
  • 2
    SQL Injection alert - you should not concatenate together your SQL statements - use parametrized queries instead to avoid SQL injection Commented Jan 20, 2017 at 17:06
  • 1
    @marc_s Ok, I didn't realise this could pose a security risk, thanks for pointing out. Commented Jan 20, 2017 at 17:16

2 Answers 2

1

Give it a try as suggested in the comments

while (reader.Read())
{
    list.Add(reader.GetInt32(0).ToString());
}

The type of data on 0th index should be an integer which should be converted to a string before adding to the list.

Sign up to request clarification or add additional context in comments.

Comments

1

If you want a more generic way to convert any single-column result set to a list of strings you can use:

while (reader.Read())
{
    list.Add(reader.GetValue(0).ToString());
}

1 Comment

Ok, that might just come in handy later on. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.