locked
Please Help??? System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid

    Question

  • I have these errors when creating my website, can anyone help me fix this problem please?

     

     Error 1

     

    Server Error in '/ Application. -------------------------------------------------------------------------------- Conversion from type 'DBNull' to type 'String' is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid. Source Error: Line 64:

    Line 65:

    Line 66: Line 67:

    Line 68:

    Source File: C:\Documents and Settings\My Documents\Visual Studio 2005\WebSites\Heat 2007\Locations_Picker.ascx Line: 66 Stack Trace: [InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.] Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value) +591 ASP.LocationsPicker.__DataBinding__control3(Object sender, EventArgs e) in C:\Documents and Settings\My Documents\Visual Studio 2005\WebSites\Heat 2007\Locations_Picker.ascx:66 System.Web.UI.Control.OnDataBinding(EventArgs e) +99 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +206 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.WebControls.FormView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +2176 System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +59 System.Web.UI.WebControls.FormView.PerformDataBinding(IEnumerable data) +9 System.Web.UI.WebControls.DataBoundControl.OnDataSourceViewSelectCallback(IEnumerable data) +111 System.Web.UI.DataSourceView.Select(DataSourceSelectArguments arguments, DataSourceViewSelectCallback callback) +29 System.Web.UI.WebControls.DataBoundControl.PerformSelect() +149 System.Web.UI.WebControls.BaseDataBoundControl.DataBind() +70 System.Web.UI.WebControls.FormView.DataBind() +4 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.WebControls.FormView.CreateChildControls(IEnumerable dataSource, Boolean dataBinding) +2176 System.Web.UI.WebControls.CompositeDataBoundControl.PerformDataBinding(IEnumerable data) +59 System.Web.UI.WebControls.FormView.PerformDataBinding(IEnumerable data) +9 System.Web.UI.WebControls.FormView.EnsureDataBound() +128 System.Web.UI.WebControls.CompositeDataBoundControl.CreateChildControls() +69 System.Web.UI.Control.EnsureChildControls() +87 System.Web.UI.Control.FindControl(String id, Int32 pathOffset) +21 System.Web.UI.Control.FindControl(String id) +9 ASP.events_edit_aspx.Page_Load(Object sender, EventArgs e) in C:\Documents and Settings\Blair Jolie\My Documents\Visual Studio 2005\WebSites\Heat 2007\Events_Edit.aspx:25 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +15 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +34 System.Web.UI.Control.OnLoad(EventArgs e) +99 System.Web.UI.Control.LoadRecursive() +47 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1
    ------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
     
     
     
    Error 2
     
     
     
    Server Error in '/ Application. -------------------------------------------------------------------------------- Conversion from type 'DBNull' to type 'String' is not valid. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid. Source Error: Line 96:

    Line 97:

    Line 98: Line 99:

    Line 100:
    Source File: C:\Documents and Settings\My Documents\Visual Studio 2005\WebSites\Heat 2007\Locations_List.aspx Line: 98 Stack Trace: [InvalidCastException: Conversion from type 'DBNull' to type 'String' is not valid.] Microsoft.VisualBasic.CompilerServices.Conversions.ToString(Object Value) +591 ASP.locations_list_aspx.__DataBinding__control14(Object sender, EventArgs e) in C:\Documents and Settings\My Documents\Visual Studio 2005\WebSites\Heat 2007\Locations_List.aspx:98 System.Web.UI.Control.OnDataBinding(EventArgs e) +99 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +206 System.Web.UI.Control.DataBind() +12 System.Web.UI.Control.DataBindChildren() +216 System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216 System.Web.UI.Control.DataBind() +12 System.Web.UI.WebControls.Repeater.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem) +130 System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +454 System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +53 System.Web.UI.WebControls.Repeater.DataBind() +72 System.Web.UI.WebControls.Repeater.EnsureDataBound() +55 System.Web.UI.WebControls.Repeater.OnPreRender(EventArgs e) +12 System.Web.UI.Control.PreRenderRecursiveInternal() +77 System.Web.UI.Control.PreRenderRecursiveInternal() +161 System.Web.UI.Control.PreRenderRecursiveInternal() +161 System.Web.UI.Control.PreRenderRecursiveInternal() +161 System.Web.UI.Control.PreRenderRecursiveInternal() +161 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1360 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
    Wednesday, May 16, 2007 3:20 AM

Answers

  • Blairj,

    Conversion from type 'DBNull' to type 'String' is not valid error occurs when you try to convert a null value to a string.

    When any of the values that you retrieve from the database is null and you try to cast the value into a string, the castException will be thrown

     

    You can workaround this by either of the Following ways

     

    1. make the value in the database as Non-null

    2. While selecting the value itself, set a value for the Null fields

    SELECT
       ISNULL(<column>, <value to use>) as [name]
    From Table

    3. In the code-behind, you could compare the value against Dbnull.value and then do a conversion to string if it is not a DBnull

     

    SanDoty

    Wednesday, May 16, 2007 3:52 AM

All replies

  • Blairj,

    Conversion from type 'DBNull' to type 'String' is not valid error occurs when you try to convert a null value to a string.

    When any of the values that you retrieve from the database is null and you try to cast the value into a string, the castException will be thrown

     

    You can workaround this by either of the Following ways

     

    1. make the value in the database as Non-null

    2. While selecting the value itself, set a value for the Null fields

    SELECT
       ISNULL(<column>, <value to use>) as [name]
    From Table

    3. In the code-behind, you could compare the value against Dbnull.value and then do a conversion to string if it is not a DBnull

     

    SanDoty

    Wednesday, May 16, 2007 3:52 AM
  • im sorry, but this is all new to me, if theres a way to explain in laymans terms it would be greatly appreciated, and thankyou for answering my post....if there is no way to explain it to me i will try to figure it out .......thanks again.
    Saturday, May 19, 2007 3:25 PM
  • Withotu seeing the code I can only suggest that it is likely you are trying to use an "empty" database value (i.e. the value in the datbase in null) as though it were a null string (a valid string which contains no characters).  You need to check for null values before you use the database value.  Try some thing like this:

     

    Dim sResult as String = ""

    If Not IsDBNull( DBField) Then sResult = DBField.ToString()

     

    This will give you a null string if the databse value is DBNull and avoid the error.

    Tuesday, May 22, 2007 10:36 PM
  •    Private Sub exportExcel(ByVal grdView As DataGridView, ByVal fileName As String, ByVal fileExtension As String, ByVal filePath As String)

     

            ' Choose the path, name, and extension for the Excel file

            Dim myFile As String = filePath & "\" & fileName & fileExtension

            Dim fs As New IO.StreamWriter(myFile, False)

     

            ' Open the file and write the headers

     

            fs.WriteLine("<?xml version=""1.0""?>")

            fs.WriteLine("<?mso-application progid=""Excel.Sheet""?>")

            fs.WriteLine("<ss:Workbook xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet"">")

            ' Create the styles for the worksheet

            fs.WriteLine("  <ss:Styles>")

            ' Style for the column headers

            fs.WriteLine("    <ss:Style ss:ID=""1"">")

            fs.WriteLine("      <ss:Font ss:Bold=""1""/>")

            fs.WriteLine("      <ss:Alignment ss:Horizontal=""Center"" ss:Vertical=""Center"" " & _

                "ss:WrapText=""1""/>")

            fs.WriteLine("      <ss:Interior ss:Color=""#C0C0C0"" ss:Pattern=""Solid""/>")

            fs.WriteLine("    </ss:Style>")

            ' Style for the column information

            fs.WriteLine("    <ss:Style ss:ID=""2"">")

            fs.WriteLine("      <ss:Alignment ss:Vertical=""Center"" ss:WrapText=""1""/>")

            fs.WriteLine("    </ss:Style>")

            fs.WriteLine("  </ss:Styles>")

            ' Write the worksheet contents

            fs.WriteLine("<ss:Worksheet ss:Name=""Sheet1"">")

            fs.WriteLine("  <ss:Table>")

            For i As Int32 = 0 To grdView.Columns.Count - 1

                fs.WriteLine(String.Format("    <ss:Column ss:Width=""{0}""/>", _

                grdView.Columns.Item(i).Width))

            Next

            fs.WriteLine("    <ss:Row>")

            '............................................................................

            For i As Int32 = 0 To grdView.Columns.Count - 1

                fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""1"">" & _

                    "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _

                    grdView.Columns.Item(i).HeaderText))

            Next

            '............................................................................

            fs.WriteLine("    </ss:Row>")

     

            ' Check for an empty row at the end due to Adding allowed on the DataGridView

            Dim subtractBy As Integer, cellText As String

            If grdView.AllowUserToAddRows = True Then subtractBy = 2 Else subtractBy = 1

            ' Write contents for each cell

            For i As Integer = 0 To grdView.RowCount - subtractBy

                fs.WriteLine(String.Format("    <ss:Row ss:Height=""{0}"">", _

                    grdView.Rows(i).Height))

                For intCol As Integer = 0 To grdView.Columns.Count - 1

     

                 

                    'I added a zero to avoid the error when exporting this to Excel from your help

                    'I don't know if it helped Blairj?

     

                    If IsDBNull(grdView.Item(intCol, i).Value) Then grdView.Item(intCol, i).Value = 0

     

                    cellText = grdView.Item(intCol, i).Value

                    ' Check for null cell and change it to empty to avoid error

                    'If cellText = "DBNull" Then cellText = "0"

                    fs.WriteLine(String.Format("      <ss:Cell ss:StyleID=""2"">" & _

                        "<ss:Data ss:Type=""String"">{0}</ss:Data></ss:Cell>", _

                        cellText.ToString))

                Next

                fs.WriteLine("    </ss:Row>")

            Next

            ' Close up the document

            fs.WriteLine("  </ss:Table>")

            fs.WriteLine("</ss:Worksheet>")

            fs.WriteLine("</ss:Workbook>")

            fs.Close()

            'open the file in microsoft excel

            ' 10 = SW_SHOWDEFAULT

            ShellEx(Me.Handle, "Open", myFile, "", "", 10)

        End Sub

     

    • Edited by Armando71 Saturday, July 04, 2009 12:36 AM
    Saturday, July 04, 2009 12:22 AM
  • This happens when the system date is not in the correct format
    Most of the time it has to be in MM-dd-yy and your date would have
    been in dd-MM-YY

    This is how you fix it

    Start->ControlPanel
    Regional & language Options
    click on customize
    select date tab

    change Short Date Format to - MM/dd/yyyy

    You are good to go. I am not sure if you have to reboot the machine. If it
    dosent work then just reboot your machine.

    Read More

    http://muruganad.com/ASP.NET/ASP_.NET_Error_Exception_Conversion_from_string_07182009_to_type_Date_is_not_valid.html

    Thanks!
    Murugan Andezuthu Dharmaratnam  
    Sunday, August 30, 2009 2:22 PM