Click here to Skip to main content
15,901,001 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is wrong with the coding, when i try to run, it say invalidcastexception : Conversion from type 'DBNull' to type 'String' is not valid. what i have to do

What I have tried:

Public Class frm_invoice_a155960

Dim i As String

Private Sub frm_invoice_a155960_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub refresh_grid()

Dim last_id As String = run_sql_query(" SELECT MAX(FLD_ORDER_ID) AS LAST_ID FROM TBL_ORDER_LIST_A155960").Rows(0).Item("LAST_ID")
Dim last_customer As String = run_sql_query(" SELECT MAX(FLD_CUSTOMER_ID) AS LAST_NAME FROM TBL_ORDER_A155960").Rows(0).Item("LAST_NAME")
Dim last_date As String = run_sql_query(" SELECT MIN(FLD_ORDER_DATE) AS LAST_DATE FROM TBL_ORDER_A155960").Rows(0).Item("LAST_DATE")
lbl_order.Text = "" & last_id
iname.Text = "" & last_customer
lbl_date.Text = "" & last_date

Dim mysql As String = " SELECT * FROM TBL_ORDER_LIST_A155960 WHERE FLD_ORDER_ID LIKE ""%" & lbl_order.Text & "%"""
Dim mydatatable As New DataTable
Dim myreader As New OleDb.OleDbDataAdapter(mysql, myconnection)

grd_invoice.DataSource = mydatatable

grd_invoice.Columns(0).HeaderText = "ID PRODUCT"
grd_invoice.Columns(1).HeaderText = "ID ORDER"
grd_invoice.Columns(2).HeaderText = "QUANTITY"
grd_invoice.Columns(3).HeaderText = "PRICE (RM)"
grd_invoice.Columns(4).HeaderText = "SUBTOTAL (RM)"

End Sub

Private Sub refresh_grid2()

Dim total As String = 0
For I As Integer = 0 To grd_invoice.RowCount - 1
total += grd_invoice.Rows(I).Cells(4).Value


lbl_total.Text = "RM " & total

End Sub
End Class
Updated 30-Nov-16 8:24am

1 solution

First off, don't do it like that.
Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use parametrized queries instead.

Secondly, to get rid of your problem, fix your database. One or more columns in your table has at least one entry which is null, and that is being returned. This arrives back from SQL as DBNull.Value and that can't be changed into a string. The best fix is to find out where the null is - and it could be in any of several places - using the debugger and find out why your DB contains values that are NULL, and fixing them.
We can't do that for you: we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900