2013-11-02 47 views
0

两个问题:C# - 搜索跨越多个列

  1. 你会如何合并代码的两位?似乎有点多余,让他们作为两个大块!

  2. 你将如何去搜索多个列(并返回结果,如果它在以下任何列中找到:名称,性别,年龄)?

    private void button1_Click(object sender, EventArgs e) 
    { 
         BindingSource bs = new BindingSource(); 
         bs.DataSource = dataGridView1.DataSource; 
         bs.Filter = "id like '%" + textBox1.Text + "%'"; 
         dataGridView1.DataSource = bs; 
    } 
    
    private void textBox1_TextChanged(object sender, EventArgs e) 
    { 
         BindingSource bs = new BindingSource(); 
         bs.DataSource = dataGridView1.DataSource; 
         bs.Filter = "id like '%" + textBox1.Text + "%'"; 
         dataGridView1.DataSource = bs; 
    } 
    
+2

为什么你不能写一个函数,并调用它,而不是写它多次的? –

+0

@Sudhakar我很新的C# – theshizy

+0

是你的代码的[SQL注入](http://xkcd.com/327/)所需的功能?请使用参数化的SQL查询。 –

回答

1

回答你的第一个问题:

创建功能,让你的搜索语句,并调用它,只要你required.as如下:

 private void button1_Click(object sender, EventArgs e) 
     { 
      SearchData(); 
     } 

     private void textBox1_TextChanged(object sender, EventArgs e) 
     { 
      SearchData(); 
     } 
     private void SearchData() 
     { 
      BindingSource bs = new BindingSource(); 
      bs.DataSource = dataGridView1.DataSource; 
      bs.Filter = "id like '%" + textBox1.Text + "%'"; 
      dataGridView1.DataSource = bs; 
     } 

回答到你的第二个问题:

你可以写如下筛选:

bs.Filter = "id like '%" + textBox1.Text + "%' and name like '%" + textBox2.Text + "%'";