Solved

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

Posted on 2013-06-29
10
1,364 Views
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


Thanks!
0
Comment
Question by:dave_sky
10 Comments
 
LVL 12

Expert Comment

by:mwochnick
Comment Utility
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

0
 
LVL 12

Expert Comment

by:funwithdotnet
Comment Utility
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

0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
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
0
 

Author Comment

by:dave_sky
Comment Utility
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!
0
 

Author Comment

by:dave_sky
Comment Utility
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...
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 27

Expert Comment

by:Ark
Comment Utility
Did you try
strUpperValue = GetDBString(TblBasicPlumbingWorkorderDataGridView.CurrentCell.Value)
0
 

Accepted Solution

by:
dave_sky earned 0 total points
Comment Utility
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!
0
 
LVL 27

Expert Comment

by:Ark
Comment Utility
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

0
 

Author Comment

by:dave_sky
Comment Utility
Not textbox, but datagridview column to uppercase...

the code I have is working fine...

Thanks!
0
 

Author Closing Comment

by:dave_sky
Comment Utility
I accepted my comment as a solution because no other comments worked.
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Introduction When many people think of the WebBrowser (http://msdn.microsoft.com/en-us/library/2te2y1x6%28v=VS.85%29.aspx) control, they immediately think of a control which allows the viewing and navigation of web pages. While this is true, it's a…
If you need to start windows update installation remotely or as a scheduled task you will find this very helpful.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

763 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

Need Help in Real-Time?

Connect with top rated Experts

8 Experts available now in Live!

Get 1:1 Help Now