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;
Without changing that much your code, you could set the row.Visible
property to false
instead of just changing row.Selected
. Anyway, the answer above is more performant and clean, you should try that.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.