If your intention is to be able to ignore the criteria, if the user leaves the field blank, you actually need to pass a NULL value to the request in this case. Just like String.Empty and Nothing not the same in VB, so an empty string and NULL are not the same in SQL. You would need to do something like this:
Dim sql = <sql> SELECT * FROM MyTable WHERE (@Column1 IS NULL OR Column1 = @Column1) AND (@Column2 IS NULL OR Column2 = @Column2) </sql> myCommand.CommandText = sql.Value Dim column1 = TextBox1.Text.Trim() Dim column2 = TextBox2.Text.Trim() With myCommand.Parameters .Add("@Column1", SqlDbType.VarChar).Value = If(column1 = String.Empty, CObj(DBNull.Value), column1) .Add("@Column2", SqlDbType.VarChar).Value = If(column2 = String.Empty, CObj(DBNull.Value), column2) End With
Note that parameters are added using Add , not AddWithValue , because the data type cannot be inferred from DBNull.Value
source share