在ListBox中显示SQL结果

时间:2015-08-20 19:50:27

标签: c# sql .net

我想在列表框中显示查询。以下是我的目标:

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;
    }
}

此时它说,没有列KSOK。我做错了什么?

3 个答案:

答案 0 :(得分:4)

如果KSOK是您要搜索的字符串,则需要引用它:

string query = "SELECT Name FROM People WHERE KnownFrom = 'KSOK'"
                                                       // ^    ^ quotes

答案 1 :(得分:1)

如果您想使用参数,就像您已注释掉的那样,您可以执行以下操作(使用ListBox2.SelectedItem.ToString()从UI获取值):

command.Parameters.AddWithValue("@KnownFrom", ListBox2.SelectedItem.ToString()); //Edited to use value from UI.

然后,将@变量添加到KSOK的查询字符串中:

string query = "SELECT Name FROM People WHERE KnownFrom = @KnownFrom";

答案 2 :(得分:0)

尝试改变,

string query = "SELECT Name FROM People WHERE KnownFrom = KSOK";

string query = "SELECT Name FROM People WHERE KnownFrom = 'KSOK'";

当您将字符串文字作为查询的一部分时,它们应该用单引号'包装。