In this vb.net form, I've created a login form which contains 3 fields:
1. User Name
2. Password
3. Combobox to select which which department the user belongs to.
For combobox, I've created a particular code:

Private Sub Form3_Load(sender As Object, e As EventArgs) Handles MyBase.Load

        cn.Open()
        'da = New SqlDataAdapter("select user_dept from user_master", cn)
        'da.Fill(ds, "user_master")
        'ComboBox1.Items.Clear()
        da = New SqlDataAdapter("select user_dept from user_master", cn)
        da.Fill(ds, "user_master")
        ComboBox1.DataSource = ds.Tables("user_master")
        ComboBox1.DisplayMember = "user_dept"
        MetroComboBox1.DataSource = ds.Tables("user_master")
        MetroComboBox1.DisplayMember = "user_dept"
    End Sub

On button click, I've done the following code:

 da = New SqlDataAdapter("select user_name,user_pass,user_dept from user_master", cn)
        da.Fill(ds, "user_master")
        dt = ds.Tables("user_master")
        For Each dr In ds.Tables(0).Rows
            If dr(0) = txtuname.Text And dr(1) = txtpw.Text And dr(2) = MetroComboBox1.Text Then
                s = 1
                Exit For
            Else
                s = 2
            End If
        Next
        If s = 1 Then
            MsgBox("Login Successful")
        ElseIf s = 2 Then
            MsgBox("Invalid Username or Password")
        End If
    End Sub


Still, this Exception Occurs:
An unhandled exception of type 'System.InvalidCastException' occurred in Microsoft.VisualBasic.dll

Additional information: Operator '=' is not defined for type 'DBNull' and string "some name or password".

It appears to me that one or more fields in one or more rows is empty, which is throwing the cast exception. Try using the Is operator instead of =:

If dr(0) Is txtuname.Text AndAlso dr(1) Is txtpw.Text AndAlso dr(2) Is MetroComboBox1.Text Then

On a side note, using AndAlso allows for shortcutting. As soon as a false value, from a comparison, is returned, the rest don't have to be read.

Also, by declaring dr as DataRow and having Option Strict turned ON, this kind of error would have been caught by Intellisense, before you even tried to run the code.

The DBNull is a special case and you'll need to do a check for it with:
If Not IsDBNull(dr(0))
and contine from there.

The Is operator handles that without any extra if statements.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.