Reputation: 15
I would like to show a query in a listbox. Here is what I have to far:
private void PopulatePeople()
{
string query = "SELECT Name FROM People WHERE KnownFrom = KSOK";//@KnownFrom";
using (connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
//command.Parameters.AddWithValue("@KnownFrom", listBox1.SelectedItem);
DataTable PeopleDT = new DataTable();
adapter.Fill(PeopleDT);
listBox2.DisplayMember = "Name";//+"Surname";
//listBox2.ValueMember = "Id";
listBox2.DataSource = PeopleDT;
}
}
At this point it says, that there is no column KSOK
. What am I doing wrong?
Upvotes: 0
Views: 177
Reputation:
try to change,
string query = "SELECT Name FROM People WHERE KnownFrom = KSOK";
to
string query = "SELECT Name FROM People WHERE KnownFrom = 'KSOK'";
When you have string literal as part of your queries, they should be wrapped by single quotes '
.
Upvotes: 0
Reputation: 464
If you would like to use Parameters, like you had commented out, you can do the following (using ListBox2.SelectedItem.ToString() to get the value from the UI):
command.Parameters.AddWithValue("@KnownFrom", ListBox2.SelectedItem.ToString()); //Edited to use value from UI.
Then, add the @ variable to your query string for KSOK:
string query = "SELECT Name FROM People WHERE KnownFrom = @KnownFrom";
Upvotes: 1
Reputation: 54877
If KSOK
is the string you are searching for, then you need to quote it:
string query = "SELECT Name FROM People WHERE KnownFrom = 'KSOK'"
// ^ ^ quotes
Upvotes: 4