Visual Basic Or, OrElse still returning false - vb.net

I am new to VB.net and i have little problem with this statement, i want to throw msgBox just if in txtBox txtTitul is not "Bc." or "" or "Ing." ...
and this is throwing msgBox everytime
If Not txtTitul.Text.Equals("Bc.") _
OrElse Not txtTitul.Text.Equals("") _
OrElse Not txtTitul.Text.Equals("Bc.") _
OrElse Not txtTitul.Text.Equals("Mgr.") _
OrElse Not txtTitul.Text.Equals("Ing.") _
OrElse Not txtTitul.Text.Equals("Mgr. art.") _
OrElse Not txtTitul.Text.Equals("Ing. arch.") _
OrElse Not txtTitul.Text.Equals("MUDr.") _
OrElse Not txtTitul.Text.Equals("MVDr.") _
OrElse Not txtTitul.Text.Equals("RNDr.") _
OrElse Not txtTitul.Text.Equals("PharmDr.") _
OrElse Not txtTitul.Text.Equals("PhDr.") _
OrElse Not txtTitul.Text.Equals("JUDr.") _
OrElse Not txtTitul.Text.Equals("PaedDr.") _
OrElse Not txtTitul.Text.Equals("ThDr.") Then
MsgBox("Neplatny titul!")
Exit Sub
End If

You don't want to use OrElse but AndAlso, because only if it's not one of those it's an invalid title (so not 1st and not 2nd and not 3rd and so on....).
But can i show you a much simpler and more maintainable approach?
Dim allowedTitles = {"Bc.","Ing.","Ing. arch.","MUDr.","MVDr.","RNDr.","PhDr.","PaedDr.","ThDr."}
If Not allowedTitles.Contains(txtTitul.Text) Then
MsgBox("Invalid title!")
End If
If you also want to accept lower-case, so ignore the case, you can use:
If Not allowedTitles.Contains(txtTitul.Text, StringComparer.InvariantCultureIgnoreCase) Then
MsgBox("Invalid title!")
End If

Consider your input is "Bc."
Not txtTitul.Text.Equals("Bc.") <- false
Not txtTitul.Text.Equals("") <- true
false OrElse true = true
Consider your input is "abc"
Not txtTitul.Text.Equals("Bc.") <- true
Not txtTitul.Text.Equals("") <- true
true OrElse true = true
For solution, you may consider Tim's answer.

Related

If statement in vb.net

In my If-statement I have 6 conditions to test. Is there any way to mininmize this code below?
If (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("_default") AndAlso (Convert.ToInt32(Request.QueryString("numFormNumber")) = 1) AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("RequiredOwner_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbConsequence_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbLikelihood_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbSeverity_default") Then
End If
I don't know enough about the logic of you "if" condition, but you can make the code more clean if you will use variables for repeated code.
Dim strControlId As String = DataBinder.Eval(item, "strControlId")).ToString
If (strControlId.Contains("_default")_
AndAlso (Convert.ToInt32(Request.QueryString("numFormNumber")) = 1) _
AndAlso Not (strControlId.Contains("RequiredOwner_default")_
AndAlso Not (strControlId.Contains("cmbConsequence_default") _
AndAlso Not (strControlId.Contains("cmbLikelihood_default")_
AndAlso Not (strControlId.Contains("cmbSeverity_default") Then

reader with blank or null records

Thought the code would catch empty records but it turns out it has not been and no error.
turns out my function always returns FALSE
Try
conn.Open()
Dim strQuery As String = "Select * FROM [UsersDataTbl] " & _
"WHERE [UserName] = """ & UserName & """"
Dim comm As New Data.OleDb.OleDbCommand(strQuery, conn)
Dim reader As Data.OleDb.OleDbDataReader = comm.ExecuteReader()
While reader.Read()
If noNull(reader("StudentID") = "") _
Or noNull(reader("LastName") = "") _
Or noNull(reader("FirstName") = "") _
Or noNull(reader("Affiliation") = "") Then
BlankFields = True
Else
BlankFields = False
End If
End While
conn.Close()
Catch ex As Exception
ADDED:
found my noNull method:
Public Function noNull(ByRef o As Object) As String
If (o Is Nothing) Then
Return ""
End If
Return o.ToString()
End Function
I process recordfield values like this:
Dim iVal As Integer = NoNull(r.Fields("someintegerfield").Value, "0", False)
Public Function NoNull(ByVal uAny As Object, Optional ByVal uFillString As String = "", Optional ByVal uTreatDecimalNullAsNothing As Boolean = False) As String
Dim sRet As String = String.Empty
If Not Convert.IsDBNull(uAny) AndAlso Not uAny Is Nothing Then
Debug.Assert(uAny.GetType.ToString <> "cField") 'checking if the argument is a "cField" helps me to check whether I passes "r.fields("somefield").value to this function, or if I forgot the ".value")
sRet = uAny
Else
sRet = String.Empty
End If
If StrLen(sRet) = 0 Then
If modStrings.StrLen(uFillString) > 0 Then
sRet = uFillString
End If
End If
If uTreatDecimalNullAsNothing Then
If sRet = "0" Then
sRet = uFillString
End If
End If
Return sRet
End Function
Public Function StrLen(ByVal uString As String) As Integer
If (Not uString Is Nothing) AndAlso (Not uString = "") Then
Return uString.Length
Else
Return 0
End If
End Function
I hope this can help you.
Dim con As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=H:\yourDB.accdb;")
Dim cb As String = "SELECT * FROM Table1 "
Dim dr As System.Data.OleDb.OleDbDataReader
Dim cmd As New System.Data.OleDb.OleDbCommand
cmd.Connection = con
cmd.CommandText = cb
con.Open()
dr = cmd.ExecuteReader
While dr.Read()
If Not IsDBNull(dr("value1")) Then MessageBox.Show(dr("value1"))
End While
con.Close()
Supposing that the noNull method is something like this
Public Function noNull(dbValue As Object) as Boolean
if dbValue = DBNull.Value OrElse dbValue = "" Then
return True
else
return False
End If
End Function
Then you call it with
....
noNull(reader("LastName") = "")
....
This means that you compare the value of the LastName field to an Empty string and the result is a boolean True or False, but passing a Boolean value to noNull means that it will never be equal to an empty string or to a DBNull.Value and thus it will return always false
You need to call the method with
If noNull(reader("StudentID")) _
Or noNull(reader("LastName")) _
Or noNull(reader("FirstName")) _
Or noNull(reader("Affiliation")) Then
Or without the noNull method
If reader.IsDBNull(reader.GetOrdinal("StudentID")) _
OrElse reader("StudentID") = "" _
OrElse reader.IsDBNull(reader.GetOrdinal("LastName")) _
OrElse reader("LastName") = ""
OrElse reader.IsDBNull(reader.GetOrdinal("FirstName")) _
OrElse reader("FirstName") = "" _
OrElse reader.IsDBNull(reader.GetOrdinal("Affiliation")) _
OrElse reader("Affiliation") = "" Then
BlankFields = True
Else
BlankFields = False
End If
As you can see this is really ugly, so I suppose that a method like noNull iomplemented above could be useful in this context
EDIT Now, looking at the code of your noNull method then it is clear where is the error.
You should just change the parenthesis position.
If noNull(reader("StudentID")) = "" _
Or noNull(reader("LastName")) = "" _
Or noNull(reader("FirstName")) = "" _
Or noNull(reader("Affiliation")) = "" Then

Linq Select with Where based on Dropdown values

I have a search page that has a series of 3 dropdowns that the user can use to limit the search results. Each of the dropdowns has an initial value of ALL. If any have a value other than ALL I need to include that as a WHERE statement.
This is where I become stuck. My Linq Select is...
Dim myComponents = From searchComponents In dc.Components _
Where searchComponents.Type = ddl_Type.SelectedValue _
AndAlso searchComponents.Size = ddl_Size.SelectedValue _
AndAlso searchComponents.WR = ddl_WR.SelectedValue _
Select searchCompnents)
At the moment my search will include all ddl selectedValues. I need to remove any that have a value of ALL. I hope I've explained correctly. Example if ddl_Size.SelectedValue = "ALL" then my statement would be...
Dim myComponents = From searchComponents In dc.Components _
Where searchComponents.Type = ddl_Type.SelectedValue _
AndAlso searchComponents.WR = ddl_WR.SelectedValue _
Select searchCompnents)
How can I achieve this in code. Thanks
Dim myComponents = From searchComponents In dc.Components _
Where (ddl_Type.SelectedValue = "ALL" OrElse searchComponents.Type = ddl_Type.SelectedValue) _
AndAlso (ddl_Size.SelectedValue = "ALL" OrElse searchComponents.Size = ddl_Size.SelectedValue) _
AndAlso (ddl_WR.SelectedValue = "ALL" OrElse searchComponents.WR = ddl_WR.SelectedValue) _
Select searchCompnents)

DatagridView Randomly Gets Formatting Error

I am having issues with my application where I randomly receive an error "Formatted value of the cell has a wrong type" when populating my DataGridView control.
This control is bound to a datatable which builds a list of rows from my database. I have cell formatting in place which checks for cell data and changes it accordingly. For example, if cell.value = 'x' then cell.value = y, etc. This seems to work fine for about 99% of the time, but every now and then I receive the above error. If I clear the error and refresh, the DataGridView control populates fine.
Is there anyway I can track down exactly what is causing this error?
My code looks like so...
Private Sub dgvRegisters_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgvRegisters.CellFormatting
Try
If e.RowIndex < 0 Then Exit Sub
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_Online") Then
e.FormattingApplied = True
Select Case Convert.ToInt32(dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
Case 1
e.Value = ilstVNC.Images(0)
Case Else
e.Value = ilstVNC.Images(1)
End Select
If XMLLoggingType = "Debug (All Activity)" Then CreateLog("Formatting DatagridView('Registers') " & dgvRegisters.Columns(e.ColumnIndex).Name & "(" & e.RowIndex + 1 & ")")
End If
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_OS") Then
e.FormattingApplied = True
Select Case (dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value).ToString
Case "Microsoft Windows XP Professional"
e.Value = "Win XP"
Case Else
e.Value = ""
End Select
If XMLLoggingType = "Debug (All Activity)" Then CreateLog("Formatting DatagridView('Registers') " & dgvRegisters.Columns(e.ColumnIndex).Name & "(" & e.RowIndex + 1 & ")")
End If
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_TimeZone") Then
e.FormattingApplied = True
Select Case (dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value).ToString
Case "(GMT+09:30) Adelaide"
e.Value = "Adelaide"
Case "(GMT+10:00) Brisbane"
e.Value = "Brisbane"
Case "N/A"
e.Value = ""
Case Else
e.Value = ""
End Select
If XMLLoggingType = "Debug (All Activity)" Then CreateLog("Formatting DatagridView('Registers') " & dgvRegisters.Columns(e.ColumnIndex).Name & "(" & e.RowIndex + 1 & ")")
End If
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_ComputerType") Then
e.FormattingApplied = True
Select Case (dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value).ToString
Case "AWRDACPI"
e.Value = "A-Box 122"
Case "HP Compaq dx7400 SFF", "HP Compaq dx7400 Small Form Factor.", "HP Compaq dx7400 Microtower"
e.Value = "HP DX7400"
Case "GHD385AV"
e.Value = "HP GHD385"
Case "To Be Filled By O.E.M."
e.Value = "A-Box 120"
Case Else
e.Value = "Unknown"
End Select
If XMLLoggingType = "Debug (All Activity)" Then CreateLog("Formatting DatagridView('Registers') " & dgvRegisters.Columns(e.ColumnIndex).Name & "(" & e.RowIndex + 1 & ")")
End If
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_p_pos") Or (dgvRegisters.Columns(e.ColumnIndex).Name = "r_p_updprg") Or (dgvRegisters.Columns(e.ColumnIndex).Name = "r_p_communic") Or (dgvRegisters.Columns(e.ColumnIndex).Name = "r_p_eftclt") Or (dgvRegisters.Columns(e.ColumnIndex).Name = "r_p_eftsvr") Then
e.FormattingApplied = True
Select Case Convert.ToInt32(dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value)
Case 1
e.Value = ilstStatus.Images(0)
Case Else
e.Value = ilstStatus.Images(1)
End Select
If XMLLoggingType = "Debug (All Activity)" Then CreateLog("Formatting DatagridView('Registers') " & dgvRegisters.Columns(e.ColumnIndex).Name & "(" & e.RowIndex + 1 & ")")
End If
Catch ex As Exception
If (XMLLogErrors = True And XMLLoggingType = "Custom") Or XMLLoggingType = "Debug (All Activity)" Then CreateLog(ex.Message)
If MySQLConn.State = ConnectionState.Open Then MySQLConn.Close()
End Try
End Sub
Basically this code just runs through and checks specific cells for specific values. I'm reasonably new to vb.net, but if my code was faulty then I would expect to receive the error everytime I load the DataGridView control.
Any help would be appreciated thanks.
Okay, in playing around with my code, I think I have found the cause of the problem, but not the answer.
I think the problem is when my SQL query fails to return any results (or fails to return results quick enough), my code enters into the Cell_Formatting event but errors due to no data:
Private Sub dgvRegisters_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgvRegisters.CellFormatting
Try
If e.RowIndex < 0 Then Exit Sub
If (dgvRegisters.Columns(e.ColumnIndex).Name = "r_Online") Then
e.FormattingApplied = True
Select Case Convert.ToInt32(dgvRegisters.Rows(e.RowIndex).Cells(e.ColumnIndex).Value) 'Code falls over here with Object reference not set to an instance of an object
I don't know how to prevent my code from going in to the formatting event if the dataset returns zero records, or better still, skip over the formatting if there are no records to format.

Filtering DBNull With LINQ

Why does the following query raise the error below for a row with a NULL value for barrel when I explicitly filter out those rows in the Where clause?
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not IsDBNull(row.Cal) AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not IsDBNull(row.Tran) AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not IsDBNull(row.barrel) _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Run-time exception thrown : System.Data.StrongTypingException - The value for column 'barrel' in table 'conformal' is DBNull.
How should my query / condition be rewritten to work as I intended?
By default, in strongly typed datasets, properties throw that exception if the field is null. You need to use the generated Is[Field]Null method :
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not row.IsCalNull() AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not row.IsTranNull() AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not row.IsbarrelNull() _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Or the DataRow.IsNull method :
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not row.IsNull("Cal") AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not row.IsNull("Tran") AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not row.IsNull("barrel") _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
This worked for me.
Dim query = From row As dbDataSet.conformalRow
In dbDataSet.Tables("conformal") _
Where row.Cal.Length > 0 AndAlso tiCal_drop.Text = row.Cal _
AndAlso row.Tran.Length > 0 AndAlso tiTrans_drop.Text = row.Tran _
AndAlso row.barrel.Length > 0 _
Select row.barrel