0

How can I compare two string values in VB.NET?

I've tried compare and equals functions, but it's not giving me the correct result. What I'm trying to compare is as follows. Also, is the code is correct?

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim con As New OleDb.OleDbConnection
        Dim ds As New DataSet
        Try
            con.ConnectionString = "Provider=SQLOLEDB;Data Source=HP-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=dbname"
            con.Open()
        Catch
            MsgBox("Error in connection")
        End Try

        Dim da As OleDb.OleDbDataAdapter
        Dim sql As String

        sql = "select * from patientprofile"
        da = New OleDb.OleDbDataAdapter(sql, con)
        da.Fill(ds, "patientprofile")
        Dim dr As DataRow
        Dim i As Integer
        i = 0
        With ds.Tables("patientprofile")
            For Each dr In .Rows
                If String.Equals(.rows(i).Item("name"), TextBox1.Text) Then
                    textbox1.text = .rows(i).item("age")
                End If
                i = i + 1
            Next
        End With
    End Sub

End Class

3 Answers 3

5

why not

If .rows(i).Item("name").ToString() = TextBox1.Text Then
  'Other Stuff
End If
Sign up to request clarification or add additional context in comments.

Comments

2

Just to be absolutely sure, try this:

with ds.Tables("patientprofile")
         For Each dr In .Rows
             if String.Equals(.rows(i).Item("name").ToString(), TextBox1.Text) then
                   textbox1.text=.rows(i).item("age").ToString()
             End If
             i = i + 1
         Next
      end with

1 Comment

Yes. Without the ".ToString()" it's comparing the a db field to the Textbox1.Text,. A DB Field != a string.
-2

Use this code:

If (String.Compare(.rows(i).Item("name").ToString(), TextBox1.Text) = 0) Then
   ' Do something
Else
  ' Do something else
End If

I have fixed the code now. Thanks @Moayad Mardini.

1 Comment

This will do the "do Something Else" all the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.