在列表框中显示SQL结果

本文关键字:SQL 结果 显示 列表 | 更新日期: 2023-09-27 18:09:03

我想在列表框中显示一个查询。以下是我要做的:

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。我做错了什么?

在列表框中显示SQL结果

如果KSOK是您正在搜索的字符串,那么您需要引用它:

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

如果您想使用参数,就像您已经注释掉的那样,您可以执行以下操作(使用listbox2 . selecteitem . 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";

尝试改变,

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

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

当你有字符串文字作为你的查询的一部分,他们应该由单引号'包装。