0

i have a dgvw in my winform . I have a textbox to search/filter the dgvw.I tried a lots of code to filter the dgvw.But each one came up with different problems.Now,i am trying to use this code :

Private Sub searcgcon_TextChanged(sender As Object, e As EventArgs) Handles searcgcon.TextChanged
TryCast(userdatagrid.DataSource, DataTable).DefaultView.RowFilter = String.Format("Name LIKE '{0}%' OR Name LIKE '% {0}%'", searcgcon.Text)

I applied this code without understanding . Now it gives me an error saying : Object reference not set to an instance of an object. I know i missed something.e.g. In the textchange event i applied this code, bu t as the code mentions "Userdatagrid.Datasource,DataTable",i did not declare/setup a datatable within the textchange event.Moreover,the code has """Name LIKE '{0}%' OR Name LIKE "".now here, is "NAME" the name of my db's column ?(i have multiple columns) Now on my form's load event,the dgvw loads data from a sql db.Here's the code :

 Private Sub Contact_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim cmd As New SqlCommand("Select * from Contacts", con)
    Dim adapter As New SqlDataAdapter(cmd)
    Dim table As New DataTable
    adapter.Fill(table)
    userdatagrid.DataSource = table

So, i just wanna know: 1. what am i missing ? 2. the code that i'm using to filter, is it the right code/solution ? 3. As mentioned, i have multiple columns in my db/dgvw,so how do i configure the filtering code to search in all the columns ? 4. About the USERDATAGRID.DATASOURCE,DATATABLE..i mentioned i did not set up any datatable within the textchane event , so can any one guide me what to do ?

Aousaf Rashid
  • 31
  • 1
  • 4
  • What you are missing is that, when you get a `NullRefereenceException`, you supposed to start by checking all the current references to see which one is `Nothing`. – jmcilhinney Oct 29 '17 at 04:49
  • what do i need to do sir?any line of code that i need to write? – Aousaf Rashid Oct 29 '17 at 04:58
  • You need to learn how to debug. Unlike many, [this beginners tutorial](http://www.homeandlearn.co.uk/NET/vbNet.html) has a chapter on debugging. – jmcilhinney Oct 29 '17 at 05:13
  • i know that ...so just trying to understand which object i left as a null ? is there any way to know it ? i debugged but on form load the entire code in the text change event gives me the exception..Taht's odd..why does it happen on form load ? – Aousaf Rashid Oct 29 '17 at 05:28
  • `I applied this code without understanding` You should never use code you dont understand. `TryCast` can fail and you are not checking. You could skip that by making the `DataTable` a form level object.. I am pretty sure the problem is in the Form Load. Set a breakpoint on the last line - it probably never gets there. You `con` object seems to not be initialized or open. – Ňɏssa Pøngjǣrdenlarp Oct 29 '17 at 15:01

0 Answers0