How to rectify error in Vb.Net Windows form for click on button for db connectivity issues

searchsanjaysharma
searchsanjaysharma used Ask the Experts™
on
There is a textbox txtauin and button btnuin.
The users enters the uin and click on uin and get the details.
But if txtauin is blank and user clicks on btnuin, then the error comes Object reference not set to instance of an object.

Code is here.

    Private Sub btnuin_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnuin.Click
        Try
            If (txtauin.Text.Trim() <> "") Then
                con = New SqlConnection("Data Source=172.16.3.17;Initial Catalog=testadms;User Id=sa;Password=admin#cgc;")
                s = "SELECT isnull(ahstatus,'') from mststudents where uin='" & txtauin.Text.Trim() & "'"

                If (con.State = ConnectionState.Closed) Then
                    con.Open()
                End If
                da = New SqlDataAdapter(s, con)
                dt = New DataTable

                da.Fill(dt)

                If (dt.Rows.Count = 0) Then
                    MessageBox.Show("No Record Found")
                    txtauin.Text = ""
                Else
                    'Timer1_Tick()
                    txtahstatus.Text = dt.Rows(0)(0).ToString()
                                End If
            end if

            Else
                MsgBox("Invalid UIN")
            End If
        Catch ex As Exception
            MsgBox(ex.ToString())
        Finally
            con.Close()
        End Try
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
the problem is with the code from finally

Finally
            con.Close()
End Try

The con is Nothing if there is no UIN
Most Valuable Expert 2012
Top Expert 2014
Commented:
Change

Finally
            con.Close()
End Try

to

Finally
     If Not IsNothing(con) Then
            con.Close()
     End If
End Try

Author

Commented:
great

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial