Error: Conversion from type 'DBNull' to type 'String' is not valid - vb.net

I'm working on a project where I get data from a database.
Now I get this error message:
Conversion from type 'DBNull' to type 'String' is not valid
I know what the error means, I just need a way to fix it.
I have the following code:
Private Function ParseSeamansNames(ByVal seaman As ItemsDataSet.SeamenRow) As String
If (seaman Is Nothing) Then Return String.Empty
Dim name As String
Dim firstNames() As String = Split(seaman.FirstName.Replace("-", " "))
Dim index1 As Integer = CInt(seaman.GivenNameNumber.Substring(0, 1))
Dim index2 As Integer = CInt(seaman.GivenNameNumber.Substring(1, 1))
If (index1 > firstNames.Length - 1) Then
index1 = 0
End If
If (index2 > firstNames.Length - 1) Then
index2 = 0
End If
If (index1 = 0 And index2 = 0) Then
name = seaman.FirstName
ElseIf (index1 > 0 And index2 = 0) Then
name = firstNames(index1 - 1)
ElseIf (index1 = 0 And index2 > 0) Then
name = firstNames(index2 - 1)
Else
name = firstNames(index1 - 1) & "-" & firstNames(index2 - 1)
End If
name = name & " " & seaman.LastName
Return name
End Function
I tried to change it to If (seaman Is Nothing) Then Return DBNull but I get error:
dbnull is a type and cannot be used as an expression
I don't really know how to fix it. Can anyone help me?
UPDATE:
I get this error:
[InvalidCastException: Conversion from type 'DBNull' to type 'String'
is not valid.]
Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object
Value) +715847
BUMSSeamenWebb.ItemsService.SeamenRow.get_FirstName() in C:\BUMS
LOKAL\Dev\Projects\BUMSSeamenWebb\Web
References\ItemsService\Reference.vb:51036
That line is this code:
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")> _
Public Property FirstName() As String
Get
Try
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
Catch e As Global.System.InvalidCastException
Throw New Global.System.Data.StrongTypingException("The value for column 'FirstName' in table 'Seamen' is DBNull.", e)
End Try
End Get
Set
Me(Me.tableSeamen.FirstNameColumn) = value
End Set
End Property
In particular:
Return CType(Me(Me.tableSeamen.FirstNameColumn),String)
I can't see the problem here
UPDATE 2:
This is another function that checks other columns
Private Sub SetSeamanData(ByRef itemRow As ItemsDataSet.ItemsRow, ByVal seaman As ItemsDataSet.SeamenRow)
itemRow.PersonalIdentityNumber = seaman.PersonalIdentityNumber
itemRow.Name = ParseSeamansNames(seaman)
itemRow.CitizenShipCode = seaman.CitizenshipCode
If Not seaman.IsEmailNull() Then
itemRow.EmailAddress = seaman.Email
Else
itemRow.EmailAddress = Nothing
End If
If Not seaman.IsTelephoneNull() Then
itemRow.TelephoneNumber = seaman.Telephone
Else
itemRow.TelephoneNumber = Nothing
End If
If Not seaman.IsMobiletelephoneNull() Then
itemRow.MobilephoneNumber = seaman.Mobiletelephone
Else
itemRow.MobilephoneNumber = Nothing
End If
End Sub

These generated DataRow classes are coded in such a way that if you try to read a property (column value) that has a database null value, it will throw an exception.
You are expected to check for null before attempting to read from it.
As you can tell from the message, in this case it's complaining that you are trying to read the value of FirstName, but it's null (DbNull).
Usually, when a column can be null, these DataRow classes also include a convenience function to check for null on that specific column. So in this case, ItemsDataSet.SeamenRow should also have a IsFirstNameNull function. If so, call that first, and handle that specific case. If IsFirstNameNull returns false, then you can safely read from the FirstName property.
If you have other columns that can be null in your database, you will need to follow a similar pattern.

Related

Increment in TicketNumber

Im Having trouble with regards to the increment to output a custom ticket number in my project currently im trying this code but it always show this error message "Additional information: Conversion from string to type 'Double' is not valid"
Function AutoID()
command.Connection = connection
connection.Open()
command.CommandText = "SELECT MAX(id) FROM tnumber"
If IsDBNull(command.ExecuteScalar) Then
number = 1
lblTN.Text = letters + number
Else
number = command.ExecuteScalar + 1
lblTN.Text = letters + number
End If
command.Dispose()
connection.Close()
connection.Dispose()
Return number
End Function
Private Sub btnRegular_Click(sender As Object, e As EventArgs) Handles btnRegular.Click
If letters = "HMD" Then
PictureBox1.Visible = False
lblCounterName.Text = "COUNTER 1"
lblTime.Text = Date.Now.ToString("MMMM dd, yyyy | hh:mm:ss tt")
btnPriority.Visible = False
btnRegular.Text = "PROCEED"
AutoID()
end if
I am guessing you are getting error due to the statement
number = command.ExecuteScalar + 1.
Here the command.ExecuteScalar is a string and so when you add 1 to it, it concatenates 1 to itself, and later when you try to store its value in number, then the error arises.
The error arises due to the fact that command.ExecuteScalar and number is an integer.
Before doing this operation you have to convert string to integer.
Replace that statement with this:
number = Integer.Parse(command.ExecuteScalar) + 1
Here we are converting string to integer and then adding 1 to it and later storing its value to number

SSRS Distinct LookupSet Issue

I apologize for the long post but I'm losing my mind here. I've tried looking this up but I keep getting error messages on any suggested fixes on this thread:
SSRS distinct lookupset function
I've even tried to completely recreate a similar data set in that question but keep getting issues.
This is the data set I created.
Using this in the expression box, and grouping by itemID, rackID, UseByDate
Join(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!CustomerSeqNo.Value
, "PickingList"), ",")
I get
but I would like to remove the duplicates in the LookupSet so it would just display "1".
I tried the first 2 options in that link above but they both provided an error message:
Public Shared Function RemoveDuplicates(m_Array As Object()) As String()
System.Array.Sort(m_Array)
Dim k As Integer = 0
For i As Integer = 0 To m_Array.Length - 1
If i > 0 AndAlso m_Array(i).Equals(m_Array(i - 1)) Then
Continue For
End If
m_Array(k) = m_Array(i)
k += 1
Next
Dim unique As [String]() = New [String](k - 1) {}
System.Array.Copy(m_Array, 0, unique, 0, k)
Return unique
End Function
with this expression:
=Join(Code.RemoveDuplicates(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value
, Fields!CustomerSeqNo.Value
, "PickingList")), ",")
returns this warning:
[rsRuntimeErrorInExpression] The Value expression for the textrun 'CustomerSeqNo.Paragraphs[0].TextRuns[0]' contains an error: Operator '&' is not defined for type 'Integer' and type 'CalculatedFieldWrapperImpl'. and this error
The other solution doesn't even deploy. Any help here?
Luckily for you #JMG, I just had to do this for a customer!
Here's the function:
public function DistinctValues(input() as Object) as string
dim newList as String
for each n as string in input
if InStr(newList, cstr(n) + ", ") = false
newList += cstr(n) + ", "
end if
next
return left(newList, len(newList) -2)
end function
So what it's doing is parsing through each value in the array. We are going to insert each unique value into a comma delimited string. Before doing so, we just check the string with InStr to see if that value already exists.
Make sure you cast the return value to string via CSTR(Fields!CustomerSeqNo.Value) to avoid any datatype issues. Your code should look something like this.
Code.DistinctValues(LookupSet(Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value, Fields!itemId.Value & Fields!UseByDate.Value & Fields!rackId.Value, CSTR(Fields!CustomerSeqNo.Value), "PickingList"))

Operator '=' is not defined for type 'DBNull' and type 'Boolean'.??/

I am going to count the checked and unchecked check box in my attendance but that come out in my code."Operator '=' is not defined for type 'DBNull' and type 'Boolean'.??"... pls help..your help is greatly appreciated. thanks
my code:
Next
Dim Present As Integer = 0
Dim Absent As Integer = 0
For a = 0 To Table2___lieDataGridView.RowCount - 1
For b = 0 To Table2___lieDataGridView.ColumnCount - 8
If Table2___lieDataGridView.Rows(a).Cells(b + 5).Value = True Then
Present += 1
Else
Absent += 1
End If
Next
Table2___lieDataGridView.Rows(a).Cells(10).Value = Present
Table2___lieDataGridView.Rows(a).Cells(11).Value = Absent
Present = 0
Absent = 0
Next
You need to use the IsDBNull function to check for a null value before making the comparison.
If Not IsDBNull(Table2___lieDataGridView.Rows(a).Cells(b + 5).Value) AndAlso Table2___lieDataGridView.Rows(a).Cells(b + 5).Value Then
End If
Before you compare the Value to True, you should check if the Value is NOT actually DBNull type.
It is because you happen to have null values in your database, and there is no comparative operator against boolean for that situation.
For example, look this question: Handling DBNull data in VB.Net

check which item is selected?

I try to check which data is selected in a DataGridViewComboBoxCell
Dim status As Double
For x As Integer = 0 To ATCGRID.Rows.Count - 1
If ATCGRID.Rows(x).Cells(2).Value = "Full" Then
status = 1
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Empty" Then
status = 0
ElseIf ATCGRID.Rows(x).Cells(2).Value = "Half" Then
status = 0.5
End If
MessageBox.Show(status)
Next x
But Its getting error
Conversion from string "Full" to type "Double" is not valid.
How can I solve this?
Try to Parse your type database,
Dim strSQL As String = "INSERT INTO ATTENDANCE(EMP_ID,EMP_NAME,AT_DATE,AT_STATUS,AT_REMARK)VALUES(#EMP_ID,#EMP_NAME,#AT_DATE,#AT_STATUS,#AT_REMARK)"
query = New SqlCommand(strSQL, Conn)
query.Parameters.Add("#EMP_ID",SqlDbType.Decimal)
query.Parameters.Add("#EMP_ID").Value=id
query.Parameters.Add("#EMP_NAME",SqlDbType.Varchar,100)' Parse your length
query.Parameters.Add("#EMP_NAME").Value=name
query.Parameters.Add("#AT_DATE",SqlDbType.Date)
query.Parameters.Add("#AT_DATE").Value=atdate
query.Parameters.Add("#AT_STATUS",SqlDbType.Decimal)
query.Parameters.Add("#AT_STATUS").Value=status
query.Parameters.Add("#AT_REMARK",SqlDbType.Varchar,50)
query.Parameters.Add("#AT_REMARK").Value=name
The Value in the cells is a number, so it cannot be compared that way. Try this:
If ATCGRID.Rows(x).Cells(2).Value.ToString() = "FULL" Then

coversion from string ""to double type is invalid

iam passing a textbox value(the value is 10:1:1) into a string and when iam running the application iam getting the following error "coversion from string "10:1:1" to double type is invalid". kindly find the code below and help me on the same: (also the textbox values should be greater than 0 always)
Dim strEncrypt As String = txtData.Text
If strEncrypt > 0 Then // I am getting the error here
txtEncryptedData.Text = Encrypt(strEncrypt)
Else
MessageBox.Show(
"Enter the Value greater then 0:")
End If
Thanks,
Rams
I believe you want this...
If strEncrypt.Length > 0 Then
Maybe you want:
Function Check(ByVal s As String) As Boolean
Dim parts As String()
parts = s.Split(":")
If parts.Length = 0 Then
Check = False
Else
Check = True
For Each sval As String In parts
Check = Check And Int32.Parse(sval) > 0
Next
End If
End Function
so you can use it like Check(txtData.Text).