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

Posted on 2013-06-29
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
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!


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

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

Suggested Solutions

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String ( Literal, only instead of starting and ending with w…
Introduction As chip makers focus on adding processor cores over increasing clock speed, developers need to utilize the features of modern CPUs.  One of the ways we can do this is by implementing parallel algorithms in our software.   One recent…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

733 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