且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在datagridview中进行搜索并进行过滤

更新时间:2023-02-26 19:06:49

if您只想显示过滤的行,使用 BindingSource.Filter 属性。
以下是 msdn 中的一个很好的示例/ p>

  bindingSource.Filter =columnname ='value'; 

private void button1_Click(object sender,EventArgs e)
{
string searchValue = textBox1.Text;

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
bindingSource.Filter = string.Format({0} ='{1}',YourColumnName,searchValue);
//如果您需要

过滤器使用以下

  bindingSource.RemoveFilter(); 
//或
bindingSource.Filter = null;


i have a question regarding with this code, i use a bindingsource to show the data and this code only select the row when im searching in datagridview. i want to know how can i filter the data im searching.

 private void button1_Click(object sender, EventArgs e)
    {
        string searchValue = textBox1.Text;

         dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

         try
         {
             foreach (DataGridViewRow row in dataGridView1.Rows)
             {
                 if (row.Cells[2].Value.ToString().Equals(searchValue))
                 {

                     row.Selected = true;
                     break;

                 }
             }
         }
         catch (Exception exc)
         {
             MessageBox.Show(exc.Message);
         }
    }

if you want to display only the filtered rows use BindingSource.Filter property. Here is a good sample in msdn

bindingSource.Filter = "columnname = 'value'";

private void button1_Click(object sender, EventArgs e)
{
    string searchValue = textBox1.Text;

     dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
     bindingSource.Filter = string.Format("{0} = '{1}'","YourColumnName", searchValue );
     //here you can do selection if you need
}

To remove filter use the following

bindingSource.RemoveFilter();
//or
bindingSource.Filter = null;