I have done this in the past, but I cant remember the correct way to deal with DBNULLS.
This is vb.net
The error im getting is Conversion from type 'DBNull' to type 'Integer' is not valid.
Here is the code.
Dim reader As MySqlDataReader = command.ExecuteReader
Do While reader.Read
Dim item As New clsProvider(reader.Item("MasterAccountID"), reader.Item("CompanyName"), reader.Item("Address"), reader.Item("Postcode"), reader.Item("Telephone"), reader.Item("Fax"), reader.Item("Number_of_Companies"), reader.Item("Total_Number_of_employees"), reader.Item("MainContactName"), reader.Item("MainContactPhone"), reader.Item("MainContactEmail"), reader.Item("Fee"), Convert.ToString(reader.Item("Notes")))
list.Add(item)
Loop
reader.Close()
The issue i have is that some of the items may be empty in the DB. I'm sure in the past I have done something like
convert.ToString(reader.item("Something")
But for the life of me i cant remember.
If the column is nullable, then you should check for null:
If (reader.IsDBNull(ordinal))
See IsDBNull
Perhaps
reader.item("Something").ToString()
is what you've done before?
This isn't necessarily correct but it does deal with null strings quite effectively.
Perhaps:
IFF(reader.item("Something") != DBNull.Value, reader.item("Something"), "")
You have to first check if the column value is null (check the incoming value for DBNull). Once you know that you can decide what to do next - assign null or some other default value to your variable.
I am not sure if my VB.Net is still upto the mark but something like this should help:
Dim item As New clsProvider
item.AccountId = TryCast(reader.Item("MasterAccountID"), String)
item.SomeInt= If(TryCast(reader.Item("SomeInt"), System.Nullable(Of Integer)), 0)
Use TryCast to check if cast is possible.
Related
I want to handle null condition in below code.
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
My code is getting break at
dataSet.Tables("History").Rows(0)("DiscountsAdjustments")
since its value is null. I want to replace null value with "0.00"
Please help how can I handle.
Thanks
Rahul,
You will likely need to rewrite this part of it. Here is your original code:
lstTest.Discount = If((Not dataSet.Tables("History") Is Nothing),
If(IsDBNull(dataSet.Tables("History").Rows(0)("DiscountsAdjustmentsAmount")),
"$0.00",
StringToCurrency(GetContractualDiscount(dataSet.Tables("History").Rows(0)
("DiscountsAdjustmentsAmount"), dataSet.Tables("History").Rows(0)
("DiscountsAdjustments"), dataSet.Tables("History").Rows(0)
("EstimatedCharges")))), "$0.00")
Instead of this big nested mess... why not do it this way. Note I dont have a VB debugger in front of me so there may be some slight format adjustments, so consider this pseudo code:
Is the dataset valid
If Not IsDBNull(dataSet.Tables("History"))
''We know that we have data in our dataset
''Do all your checks
if Not isDBNull(dataSet.Tables("History").Rows(0)("Your field"))
''Do something
Else
''Show a 0
END IF
''REPEAT THE ABOVE LINES FOR EACH FIELD
End if
You can check for null on any column first using methods on the DataRow object:
Which of IsDBNull and IsNull should be used?
I have a trivial question about updating a datatable MyDT. I googled and found several approach and got compile errors. Here is the code and here is what I tried with the error. Any help is greatly appreciated. BTW, I am using asp.net framework 2.0 and VB.NET
MyDT.Rows[1][4] = "4NF" ' Property access must assign to the property or use it value
row.Item("New_Column") = "4NF" ' Input string was not in a correct format.
Couldn't store <4NF> in New_Column Column. Expect type is Byte.
row["New_Column"] = "4NF" ' Expression is not a method
Dim StatusCode As String
For Each row As DataRow In MyDT.Rows
StatusCode= row.Item("ThisColumn").ToString()
If StatusCode= "NONF" Then
MyDT.Rows[1][4] = "4NF"
End If
Next row
You should either:
Store data as String in your DataTable
Do a conversion
Here how the conversion looks
MyDT.Rows[1][4] = Convert.ToByte("4NF")
I am trying to remove duplicates in a ListBox which is populated by a query pull. I use this code to prevent adding duplicates in VB 6.0 but does not work when converted over to VB.net. Is there a substitute method to prevent or remove duplicates.
colSchema = dr("Col_Schema").ToString
If Not lstSchema.Items.ToString.Contains(colSchema) Then
lstSchema.Items.Add(New ListItem(colSchema))
End If
try
colSchema = dr("Col_Schema").ToString
dim exists as boolean = false
for i as integer = 0 to lstSchema.items.count - 1
if lstSchema.items.item(i) = colSchema then
exists = true
end if
next
if exists = false then
lstSchema.Items.Add(New ListItem(colSchema))
end if
This code
lstSchema.Items.ToString
is converting Items to a string. Items is most likely the type ListBox.ObjectCollection (if this is WinForms) or a similar collection type for other UI frameworks. Calling ToString on such classes will end up calling Object.ToString, which just returns the name of the class.
Instead, try
lstSchema.Items.Contains(colSchema)
If that does not work for some reason, please update your question explaining exactly what you were trying to solve by calling ToString.
A tons of advance thanks to everybody for taking time on this!
Am I doning this correctly? it says "Parameter count mismatch." for SetValue method
For i = 0 To (missingFieldName.Count) - 1
Dim propertyiInfo As System.Reflection.PropertyInfo =
GetType(ImportFields).GetProperty(missingValuesTakenfromUser.missingFieldAcquired(i, 0))
Dim fieldacquired As String = missingValuesTakenfromUser.missingFieldAcquired(i, 1)
propertyiInfo.SetValue(fields, fieldacquired, New Object() {0})
Next i
fields is an instance of class ImportFields. tried a 100 different ways to work with this in last 2 days. desperately looking for a solution, please someone?
For a non-indexed property, the third parameter should be null, not an empty array. Try this:
propertyiInfo.SetValue(fields, fieldacquired, null);
If you use .net 4.5, there's a new overload with only two parameters that you can use instead:
propertyiInfo.SetValue(fields, fieldacquired); // .net 4.5 only
Got it after 4 days continuous struggle. here is how to do that
Many thanks to Jods for giving a tip above.
For i = 0 To (missingFieldName.Count) - 1
Dim propertyiInfo As System.Reflection.PropertyInfo =
GetType(ImportFields).GetProperty(missingValuesTakenfromUser.missingFieldAcquired(i, 0))
Dim fieldacquired As String = missingValuesTakenfromUser.missingFieldAcquired(i, 1)
propertyiInfo.GetValue(fields, Nothing)(0) = fieldacquired
Next i
actually, MS is a bit confusing when they say indexed items. it meant to me they referring to array.
thanks a lot for everybody who struggled to solve this for me.
I'm creating a gridview using an objectdatasource and it works fine when pulling all records. But when I want to use the selectCountMethod the grid shows no values.
I Step through the code and my getInvoices (gets the requested data) returns data and the getInvoicesCount (gets the total record count). But then when I go through the rowdatabound of the gridview there's nothing in there and no data displays.
Here is my code to set the objectdatasource. Any reasons why it wouldn't work or something special that needs to be done for getting the selectcount to work?
Me.ODS.TypeName = "invoice"
Me.ODS.EnablePaging = True
Me.ODS.SelectMethod = "getInvoices"
Me.ODS.SelectCountMethod = "GetInvoiceCount"
Me.ODS.StartRowIndexParameterName = "startRowIndex"
Me.ODS.MaximumRowsParameterName = "maximumRows"
Me.ODS.SelectParameters.Add("strbu", strBusUnit)
Me.ODS.SelectParameters.Add("stremailAddress", emailAddress)
Me.ODS.SelectParameters.Add("startDate", search_startdate)
Me.ODS.SelectParameters.Add("enddate", search_enddate)
Me.ODS.SelectParameters.Add("sortExpression", sortExpression & " " & sortDirection)
With gvInvoices
.PageIndex = intPageIndex
.PageSize = 25
.DataBind()
End With
Check if the count being returned is an integer . debug it . maybe it is null.
and if not null parse it to an integer
I was able to figure this one out. The count was being returned as a long instead of integer. I changed it to integer and all is working great