在窗口表单应用程序的两个下拉菜单之间搜索

本文关键字:两个 下拉菜单 之间 搜索 表单 窗口 应用程序 | 更新日期: 2023-09-27 18:32:40

我通过一个下拉菜单实现了搜索。

 private void search_Click(object sender, EventArgs e)
        {
            string query = "SELECT * FROM magzines where issue_number = '"+comboBox1.Text+"'";
            SqlDataAdapter sda = new SqlDataAdapter(query , con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            dataGridView1.Rows.Clear();
            foreach (DataRow item in dt.Rows)
            {
                int n = dataGridView1.Rows.Add();
                dataGridView1.Rows[n].Cells[0].Value = item[0].ToString();
                dataGridView1.Rows[n].Cells[1].Value = item[1].ToString();
                dataGridView1.Rows[n].Cells[2].Value = item[2].ToString();
                dataGridView1.Rows[n].Cells[3].Value = item[3].ToString();
            }
        }

请帮助我如何通过两个下拉菜单进行搜索?

在窗口表单应用程序的两个下拉菜单之间搜索

您应该更改为参数化查询以避免 SQL 注入攻击,而不是像现在这样连接 SQL 字符串。 要回答问题,请添加第二个下拉列表并在查询中使用 BETWEEN ...

string query = "SELECT * FROM magzines where issue_number BETWEEN '"+comboBox1.Text+"' AND '"+comboBox2.Text+"'";

使用参数的示例...

using (SqlConnection conn = new SqlConnection(con))
    {
      string query = "SELECT * FROM magzines where issue_number BETWEEN '@comboOne' AND '@comboTwo'";
      using (SqlCommand cmd = new SqlCommand(query, conn))
      {
        cmd.Parameters.Add("comboOne", SqlDbType.VarChar).Value = comboBox1.Text;
        cmd.Parameters.Add("comboTwo", SqlDbType.VarChar).Value = comboBox2.Text;
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
          da.Fill(table);            
      }
    }

您可以使用 BindingSource

 BindingSource source1 = new BindingSource();
source1.DataSource = view1;
// Set the data source for the DataGridView.
datagridview1.DataSource = dt ;
//The Filter string can include Boolean expressions.
source1.Filter = "artist = 'Dave Matthews' OR cd = 'Tigerlily'";

欲了解更多信息,请访问 http://msdn.microsoft.com/en-us/library/system.windows.forms.bindingsource.filter%28VS.90%29.aspx