Solved

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

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

0
 
LVL 12

Expert Comment

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

0
 
LVL 28

Expert Comment

by:Ark
ID: 39288698
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
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 

Author Comment

by:dave_sky
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."
  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
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...
0
 
LVL 28

Expert Comment

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

Accepted Solution

by:
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!
0
 
LVL 28

Expert Comment

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

0
 

Author Comment

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

the code I have is working fine...

Thanks!
0
 

Author Closing Comment

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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

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 (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

792 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