Reputation:
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.
Upvotes: 1
Views: 391
Reputation: 754388
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";
Upvotes: 2