c中的sql搜索查询

本文关键字:查询 搜索 sql 中的 | 更新日期: 2023-09-27 18:21:42

我正试图在我的应用程序中进行数据库搜索,用户可以在其中选择列并输入搜索词,结果会出现在数据视图网格中。这是我一直在处理的代码,问题是什么都没有出现,我很确定数据库中有条目。编辑:这是一个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();
    }

c中的sql搜索查询

不能使用参数来表示列的名称。您应该用列名填充组合框,并将其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];
    }
}

您忘记了将网格视图与数据源绑定将此添加到数据源之后

dataGridView1.DataSource = ds.Tables[0];
dataGridView1.DataBind();
    private void bunifuThinButton21_Click(object sender, EventArgs e)
    {
        SqlConnection connection = new SqlConnection();
        connection.ConnectionString = (@"Data Source=.'SQLEXPRESS;AttachDbFilename=C:'Users'albasheer'Desktop'games'my_school'my_school'school.mdf;Integrated Security=True;User Instance=True");
        connection.Open();
        string sql = "select name,id,stage,age,cost from STUDENT where   stage like '%" + bunifuCustomLabel1.Text + "%' and name like '%" + bunifuMaterialTextbox1.Text + "%'";
        SqlDataAdapter adapter = new SqlDataAdapter(sql, connection);
        SqlCommand command = new SqlCommand(sql, connection);

        DataTable table = new DataTable();
        adapter.Fill(table);
        var dt = from t in table.AsEnumerable()
                 select new
                 {
                     id = t.Field<int>("id"),
                     Name = t.Field<string>("name"),
                    
                 };
        bunifuCustomDataGrid1.DataSource = dt.ToList();
    }