1

I am trying to figure out how to collect data from a database with c#. I am stuck on a SQL command, and I can't really figure out how to fix it. My error is: Invalid Column Name

This is my database: MyDatabase

And this is my connection class:

namespace CarDAL
{
    public class ConnectionClass
    {
        private string Connectionstring =
            "MYCONNECTIONSTRING";


        public List<string> SoortSelectList(string KarakterSoort)
        {
            KarakterSoort = "Defensive";
            List<string> soortList = new List<string>();
            using (SqlConnection connection = new SqlConnection(Connectionstring))
            {
                connection.Open();

                using (SqlCommand cmd = new SqlCommand("SELECT * FROM dbo.Karakter WHERE KarakterSoort = Defensive", connection))
                {
                    using (IDataReader dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            soortList.Add(dr.GetValue(0).ToString());
                            soortList.Add(dr.GetValue(1).ToString());

                        }
                    }
                }
            }

            return soortList;
        }

I think after WHERE that the problem is, but I don't know (and can't find) the right solution for my problem.

1
  • In addition to @marc_s answer....your passing in a string "KarakterSoort" and then you setting the string to "Defensive"....then (I think) your trying to use that string in SELECT string. Commented Nov 1, 2020 at 19:06

1 Answer 1

2

Your WHERE clause here:

WHERE KarakterSoort = Defensive

compares the value in the KarakterSoort column to the value in the Defensive column.

Is that really what you want???

Quite possibly, you want to compare to a string literal - then you need to put this into single quotes like this:

WHERE KarakterSoort = 'Defensive'

Now you're selecting all rows where the KarakterSoort column contains the value Defensive

Or if you might want compare to some other value in the future - use a parameter in your query string:

WHERE KarakterSoort = @DesiredValue

and declare it

cmd.Parameters.Add("@DesiredValue", SqlDbType.VarChar, 100);

and set its value before your run the command:

cmd.Parameters["@DesiredValue"].Value = "Defensive";
Sign up to request clarification or add additional context in comments.

1 Comment

If it answered the question, @JosseLardinois, you should mark the answer as the solution.

Your Answer

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