Link to home
Start Free TrialLog in
Avatar of David Svedarsky
David SvedarskyFlag for United States of America

asked on

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

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


Thanks!
Avatar of mwochnick
mwochnick
Flag of United States of America image

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

Avatar of funwithdotnet
funwithdotnet

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

Avatar of Ark
Hi
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:
MsgBox(GetDBString(TblWorkorderDataGridView.CurrentCell.Value,"Missing"))
'or
Dim x as String=GetDBString(TblWorkorderDataGridView.CurrentCell.Value)
If x="" Then
   MsgBox("Null value!")
End If
Avatar of David Svedarsky

ASKER

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."
  Source="Microsoft.VisualBasic"
  StackTrace:
       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?

Thanks!
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...
Did you try
strUpperValue = GetDBString(TblBasicPlumbingWorkorderDataGridView.CurrentCell.Value)
ASKER CERTIFIED SOLUTION
Avatar of David Svedarsky
David Svedarsky
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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

Not textbox, but datagridview column to uppercase...

the code I have is working fine...

Thanks!
I accepted my comment as a solution because no other comments worked.