使用3个文本框

时间:2017-05-07 11:26:23

标签: c# winforms sqlite

我正在编写一个程序,用户可以通过3个文本框过滤数据库中的结果,但是,结果没有被正确过滤,因为如果一个框留空,它不会显示任何内容

private void textBox1_TextChanged(object sender, EventArgs e)
{
    con = new SQLiteConnection(cs);
    con.Open();

 if ((textBox2.Text==""||textBox.Text3=="")&&textBox1.Text!="")
    {
        adapt = new SQLiteAdapter("select data1, data2 from DataTable where data1 like '" + textBox1.Text + "%'", con);
        dt = new DataTable();
        adapt.Fill(dt);
        dataGridView1.Source = dt;
    }
    else if(textBox1.Text !="")
    {
        adapt = new SQLiteAdapter("select data1, data2 from DataTable where data1 like '" + textBox1.Text + "%' and data2 like '" + textBox2.Text + "%' and substr(data2,-2) like '" + textBox3.Text +"'", con);
        dt = new DataTable();
        adapt.Fill(dt);
        dataGridView1.Source = dt;

    }
con.close();
}

这是我在其中一个文本框中使用的代码,对于另外两个看起来几乎相同的代码,除了我更改if子句条件。 我是否必须为每个文本框编写9个不同的子句,以便我涵盖所有选项?有没有正确的方法?

1 个答案:

答案 0 :(得分:0)

在构造函数或Form_Load中,TextBoxes将事件更改为一个处理程序:

textBox1.TextChanged += textBox1_TextChanged;
textBox2.TextChanged += textBox1_TextChanged;
textBox3.TextChanged += textBox1_TextChanged;

并动态构建WHERE子句而不是9个条件:

con = new SQLiteConnection(cs); 
con.Open();
StringBuilder sb = new StringBuilder();

sb.Append("select * from DataTable where "); 
foreach (Control c in this.Controls) { 
TextBox t = c as TextBox; 
 if (t != null) { 
  if (t.Length > 0) {
  //In design-time set the TextBox Tag property to the SQL column name
  sb.Append(t.Tag.ToString() + " like '" + t.Text + "%' and ");
   }
  }
 }

string SQL = sb.ToString();
if (SQL.Length > 0) {
   SQL = SQL.Substring(0, SQL.Length-5);
}


adapt = new SQLiteAdapter(SQL, con); 
dt = new DataTable(); 
adapt.Fill(dt); 
dataGridView1.Source = dt;

您还应该使用存储过程或付费 参数化命令。

相关问题