Home > Back-end >  Syntax for OR expressions in Visual Basic
Syntax for OR expressions in Visual Basic

Time:11-24

I do not know Visual Basic as much as I know C or C#.

I'm going to check if a select query have any results in returned 'testDataset` and have some results, so I wrote below syntax:

If ((testDataset Is Nothing) Or (testDataset.Tables Is Nothing) Or testDataset.Tables.Count = 0 _
    Or (testDataset.Tables.Item(0).Rows Is Nothing) Or (testDataset.Tables.Item(0).Rows.Count = 0) _
    Or (testDataset.Tables.Item(0).Rows(0) Is Nothing)) Then
    MessageBox.Show("Dataset has no results!", "Database Query Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return False
End If

In C when an expression inside logical OR comes true next expression will not be processed. But it seems this is not the case in Visual Basic. So I want to know how can I check several expressions in visual basic and stop processing next ones if one came true.

So my question is mainly can be asked as two questions:

  1. How can I check several condition's using OR without processing next ones?

  2. How can I check if Dataset has results (at least one row) and an specific column is present in that (at least one) row?

CodePudding user response:

You can use the null conditional operator to short circuit all those checks in one line. The ? after the member in this chain will stop evaluating subsequent members and return null if the member is null.

Return testDataset?.Tables?.Item(0)?.Rows?.Any() ' true if any, false if none

CodePudding user response:

This is overkill on checking for Nothing. Presumably you have created a DataSet and filled it with a DataTable. The table may not have any rows returned but neither the DataSet nor the DataTable is Nothing.

If you are only using a single table, then dispense with the DataSet.

Private dt As New DataTable

Private Sub GetData()
    Using cn As New SqlConnection(ConLocal),
            cmd As New SqlCommand("Select Top 10 * From Coffees", cn)
        cn.Open()
        Using reader = cmd.ExecuteReader
            dt.Load(reader)
        End Using
    End Using
End Sub

Private Function CheckTable() As Boolean
    If dt.Rows.Count > 0 Then
        Return True
    End If
    MessageBox.Show("Dataset has no results!", "Database Query Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    Return False
End Function

CodePudding user response:

This - probably - is not an exact answer, but general advice...

The shortest way to catch error while reading data from dataset is to get a code into Try...Catch..Finally block.

Dim bRetVal As Boolean = True
Try
   'your code to read data
Catch ex As Exception
    MessageBox.Show("Something went wrong..." & vbCrLf  & vbCrLf & ex.Message, "Error while reading data", MessageBoxButtons.OK, MessageBoxIcon.Error)
    bRetVal = False
Finally
  Return bRetVal
  • Related