[Last Call] Learn about multicloud storage options and how to improve your company's cloud strategy. Register Now


Cast from type 'DBNull' to type 'String' is not valid

Posted on 2013-06-29
Medium Priority
Last Modified: 2013-07-14
How to modify code to remove error: Cast from type 'DBNull' to type 'String' is not valid valid when cell is empty?

Private Sub TblWorkorderDataGridView_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles TblWorkorderDataGridView.CellEndEdit
        Dim strUpperValue As String
        'Apply to certain columns        
        Select Case e.ColumnIndex
            Case 10 
                strUpperValue = TblWorkorderDataGridView.CurrentCell.Value
                TblWorkorderDataGridView.CurrentCell.Value = strUpperValue.ToUpper
        End Select

Open in new window

Question by:dave_sky
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 12

Expert Comment

ID: 39287633
Use an if statement to check if the cell value is null before assigning it to the string
if (Not (TblWorkorderDataGridView.CurrentCell.Value is Nothing or TblWorkorderDataGridView.CurrentCell.Value = DBNull.value))
  strUpperValue = TblWorkorderDataGridView.CurrentCell.Value

Open in new window

LVL 12

Expert Comment

ID: 39288256
Here's another way to code it ...
strUpperValue = ""
If TblWorkorderDataGridView.CurrentCell.Value IsNot Nothing AndAlso TblWorkorderDataGridView.CurrentCell.Value.Length > 0 Then
    strUpperValue = TblWorkorderDataGridView.CurrentCell.Value 
End If

Open in new window

LVL 28

Expert Comment

ID: 39288698
I'm using following function:
        Public Shared Function GetDBString(ByVal o As Object, Optional ByVal strDBNull As String = "") As String
            If o Is Nothing Then Return strDBNull
            If IsDBNull(o) Then Return strDBNull Else Return o.ToString
        End Function

Open in new window

Now you can use from anywhere:
Dim x as String=GetDBString(TblWorkorderDataGridView.CurrentCell.Value)
If x="" Then
   MsgBox("Null value!")
End If

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.


Author Comment

ID: 39288746
I tried all of the code samples above and none worked.

I get the error on this line when deleting text from a databridview cell (datatype nvarchar (3):
strUpperValue = TblBasicPlumbingWorkorderDataGridView.CurrentCell.Value

Here are the error details:
System.InvalidCastException was unhandled
  Message="Conversion from type 'DBNull' to type 'String' is not valid."
       at Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value)
       at Plumbing.frmTrackingUPBJobs.TblWorkorderDataGridView_CellEndEdit(Object sender, DataGridViewCellEventArgs e) in C:\Documents and Settings\Dave\My Documents\Visual Studio 2005\Projects\Plumbing\Plumbing\frmTrackingUPBJobs.vb:line 68
       at System.Windows.Forms.DataGridView.OnCellEndEdit(DataGridViewCellEventArgs e)
       at System.Windows.Forms.DataGridView.EndEdit(DataGridViewDataErrorContexts context, DataGridViewValidateCellInternal validateCell, Boolean fireCellLeave, Boolean fireCellEnter, Boolean fireRowLeave, Boolean fireRowEnter, Boolean fireLeave, Boolean keepFocus, Boolean resetCurrentCell, Boolean resetAnchorCell)
       at System.Windows.Forms.DataGridView.SetCurrentCellAddressCore(Int32 columnIndex, Int32 rowIndex, Boolean setAnchorCellAddress, Boolean validateCurrentCell, Boolean throughMouseClick)
       at System.Windows.Forms.DataGridView.OnCellMouseDown(HitTestInfo hti, Boolean isShiftDown, Boolean isControlDown)
       at System.Windows.Forms.DataGridView.OnCellMouseDown(DataGridViewCellMouseEventArgs e)
       at System.Windows.Forms.DataGridView.OnMouseDown(MouseEventArgs e)
       at System.Windows.Forms.Control.WmMouseDown(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.DataGridView.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at Plumbing.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

Can someone help on this?


Author Comment

ID: 39288751
All I want to do is convert the cell value to upper case and have nothing when deleted.

If I add  a binding textbox to the form - the datagridview cell formatting works fine and deletes...
LVL 28

Expert Comment

ID: 39288756
Did you try
strUpperValue = GetDBString(TblBasicPlumbingWorkorderDataGridView.CurrentCell.Value)

Accepted Solution

dave_sky earned 0 total points
ID: 39290372
I found some code that works fine:

 Private Sub TblWorkorderDataGridView_CellEndEdit(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles TblWorkorderDataGridView.CellEndEdit

        If e.ColumnIndex = 10 Then
            TblWorkorderDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value = TblWorkorderDataGridView.Rows(e.RowIndex).Cells(e.ColumnIndex).Value.ToString().ToUpper()
        End If

    End Sub

Open in new window

Thanks everyone for your efforts!
LVL 28

Expert Comment

ID: 39292221
You just want make textbox uppercase?
    Private Sub DataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles DataGridView1.EditingControlShowing
        If TypeOf e.Control Is TextBox Then
            If CType(sender, DataGridView).CurrentCell.ColumnIndex = 10 Then
                CType(e.Control, TextBox).CharacterCasing = CharacterCasing.Upper
            End If
        End If
    End Sub

Open in new window


Author Comment

ID: 39294299
Not textbox, but datagridview column to uppercase...

the code I have is working fine...


Author Closing Comment

ID: 39324401
I accepted my comment as a solution because no other comments worked.

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …
In a question here at Experts Exchange (https://www.experts-exchange.com/questions/29062564/Adobe-acrobat-reader-DC.html), a member asked how to create a signature in Adobe Acrobat Reader DC (the free Reader product, not the paid, full Acrobat produ…
Suggested Courses

650 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question