vb.net - "object cannot be cast from dbnull to other types" when select sql query runs -


i looking more "object cannot cast dbnull other types" error. can't find possible answer resolve problem.

private sub button18_click(sender object, e eventargs) handles button18.click              'query = "select sum(fuel) ttlfuel, sum(stationery) ttlstationery, sum(salary) ttlsalary, sum(v_part) ttlvp, sum(other) ttlother mcs.expenses datee between #" & dtpisf.value.tostring & "# , #" & dtpist.value.tostring & ""     dim cmd = new mysqlcommand(query, con)     dim dr mysqldatareader     try         con.open()         dr = cmd.executereader()         while dr.read()             me.txtfuel.text = convert.todecimal(dr("ttlfuel"))             ' me.txtstationary.text = convert.todecimal(dr("ttlstationery"))             'me.txtcollectorsalery.text = convert.todecimal(dr("ttlsalary"))             'me.txtvehiclepart.text = convert.todecimal(dr("ttlvp"))             'me.txtotherexpenses.text = convert.todecimal(dr("ttlother"))         end while         dr.close()         con.close()      catch ex exception         msgbox(ex.message)         try             if (con.state = connectionstate.open)                 con.close()             end if         catch ex2 exception             msgbox(ex2.message)         end try     end try 

in program had button , coded sum of each columns. , special thing want filter these data between 2 dates date time pickers. (dtpisf , dtpist). data table name expenses. it's data rows @ least had 0 values. can ?

leaving aside other problems outlined in comments (eg - using command , sqlparamemters instead of dynamic string), think current problem make assumption fields:

(a) have value ,

(b) have right type of value stored convert data type want.

you use extension method work of checking (vb.net code below):

public module datarowextension     <system.runtime.compilerservices.extension()>     function getordefault(of t)(row system.data.sqlclient.sqldatareader, name string, [default] t) t         if isdbnull(row(name))             return [default]         else             return ctype(row(name), t)         end if     end function end module 

then, can use code set values:

me.txtfuel.text = dr.getordefault(of string)("ttlfuel", "") 

or, decimal:

decimal myvalue = dr.getordefault(of decimal)("ttlfuel", 0) me.txtfuel.text = myvalue.tostring("#,##0.00") 

in addition, turn on option strict in code. if do, you'll catch problems 1 @ compile time (instead of running them @ runtime). and, if can @plutonix give answer... go it.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -