Searchbox for Windows表单应用程序c#

时间:2015-07-29 19:45:54

标签: c# windows-forms-designer

我在Windows窗体C#应用程序中为gridview实现了一个搜索框。它目前有效,但只搜索一列。这是列[1]的位置。有人可以帮我搜索gridview中的所有列我目前有15列:

private void button1_Click(object sender, EventArgs e) {
    BindingSource bs = new BindingSource();
    bs.DataSource = dataGridView1.DataSource;
    bs.Filter = dataGridView1.Columns[1].HeaderText.ToString() + " LIKE '%" + txt_search.Text + "%'";
    dataGridView1.DataSource = bs;
}

1 个答案:

答案 0 :(得分:0)

String.Format在这里运作良好。

bs.Filter = string.Format("COLUMN1 LIKE '%{0}%' OR COLUMN2 LIKE '%{0}%'", txt_search.Text);

您应匹配DataGridViewColumn名称属性,而不是 HeaderText ,因为标题文字是显示标题,无需与基础列名匹配

您可以随时迭代列来构建过滤器:

string filter = string.Empty;

foreach (DataGridViewColumn column in dataGridView1.Columns)
{
    if (column.Index == 0) 
    {
        filter += string.Format("{0} LIKE '%{1}%'", column.Name, txt_search.Text);
    }
    else
    {
        filter += string.Format(" OR {0} LIKE '%{1}%'", column.Name, txt_search.Text);
    }
}

bs.Filter = filter;