1
(ItemGridView.DataSource as DataTable).DefaultView.RowFilter = string.Format("OR Name like '{0}%'", searchBox.Text);

Trying search an item in my GridView by using the following line of code from How to search in Data gridview in C# Windows Form application? and got a System.NullReferenceException: 'Object reference not set to an instance of an object.'. Is there anything to solve this?

Very new to c# and need help.

Hiro
  • 11
  • 1
  • Does the grid use a `DataSource` … ? … The line of code … `(ItemGridView.DataSource as DataTable)` … implies the grid DOES use a data source and it is a `DataTable`. That is about the only thing I can see that could be `null`. – JohnG Apr 17 '22 at 02:08
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – JohnG Apr 17 '22 at 02:59
  • That's not a valid row filter string either . You can't start a predicate with OR; to use OR one has to have something else first, like `name = 'John' OR age = 1` – Caius Jard Apr 17 '22 at 07:34
  • The linked question uses a BindingSource as the DataSource; your code uses a DataTable. Which is true? Show us the line where you set your DataSource equal to something (show us where you assign DataSource) – Caius Jard Apr 17 '22 at 07:36
  • See the following [extension methods](https://github.com/karenpayneoregon/q-a-questions/blob/master/WinFormHelpers/LanguageExtensions/BindingSourceExtensions.cs) used here in a [form](https://github.com/karenpayneoregon/q-a-questions/blob/master/BindingSourceFiltering/Form1.cs). Code shows how to perform a starts with, ends with and a clear filter. Filtering by default here is case insensitive. – Karen Payne Apr 17 '22 at 12:26

0 Answers0