我正在尝试在我的应用程序中进行数据库搜索,用户将选择该列并输入搜索词,结果将出现在dataviewgrid中。 这是我一直在研究的代码,问题是什么都没有出现,我很确定数据库中有条目。编辑:这是一个Windows窗体应用程序
private void button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection("Server = localhost; database = Clients; Integrated Security = SSPI");
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * From dbo.Tclients WHERE @choice = @input", conn);
cmd.Parameters.AddWithValue("@choice", comboBox1.Text);
cmd.Parameters.AddWithValue("@input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
答案 0 :(得分:3)
您不能使用参数来表示列的名称。
您应该使用列名填充组合框并将其DropDownStyle
属性设置为DropDownList
(不允许用户键入列的名称),然后构建查询
private void button1_Click(object sender, EventArgs e)
{
string cmdText = "SELECT * From dbo.Tclients WHERE " + comboBox1.Text + " = @input";
using(SqlConnection conn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("@input", textBox1.Text);
ds = new DataSet();
da = new SqlDataAdapter(cmd);
da.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
}
答案 1 :(得分:0)
您忘记使用数据源绑定网格视图 在数据源
之后添加dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();