Search for value in DataGridView in all columns

Viewed 31

Hi i want to search in all rows. My code is here;

try
                {
                    var searchValue = textBox1.Text;
                    var colName = dataGridView1.Columns[1].Name;//Column Number of Search
                    var value = "CONVERT("+colName+", System.String) like '%{0}%'";
                    ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Format(value, searchValue.Trim().Replace("'", "''"));
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message);
                }
1 Answers

Ideally, you wouldn't search the grid itself, you would search the underlying data source, which should avoid the need to convert data types. You could also use Linq, which (in my opinion at least) is one of the most essential things a C# programmer needs to know.

Without seeing more code it's hard to say, but it makes for more robust code if you try and keep the UI and logic as decoupled as possible. That way, this sort of thing becomes easier (as you don't have to deal with the various ways different UI elements store data), and if/when (more likely when) the UI changes, the back-end logic shouldn't need to change.

Related