.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

If / IIf - Cast Exception

Posted By:      Posted Date: September 26, 2010    Points: 0   Category :ASP.Net

Hi over there,

I hope this question is not too simple, but I didn't manage to figure out why...
I would need an explanation for following issue:

I'm reading data from a database (MSSQL) and it the column "PersonBirthday" is DBNull.
I wanted to prevent the error (Textbox.Text = DBNull) with an IIF. The thing is I get this
typecast exception:

"Conversion from type 'DBNull' to type 'Date' is not valid."

 This code is NOT working, why?
   txtPersonBirthday.Text = IIf(IsDBNull(.Item("PersonBirthday")) = True, String.Empty, CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd"))

When I'm using this code, which is for me obviously the same, just with an if-block it works,
and I want to know why - please explain.

           If IsDBNull(.Item("PersonBirthday")) Then
                txtPersonBirthday.Text = String.Empty
                txtPersonBirthday.Text = CDate(.Item("PersonBirthday")).ToString("yyyy-MM-dd")

View Complete Post

More Related Resource Links

[Odd]Specified cast is not valid exception

protected float getUserBalance() { string AccountNo = Session["AccNo"].ToString(); myConnection.Open(); float balance = 0; try { OleDbCommand getBalance = new OleDbCommand("Select Balance from BankTransaction where AccountNo = '" + Session["AccNo"] + "'", myConnection); //OleDbDataReader rdrBalance = getBalance.ExecuteReader(); //while (rdrBalance.Read()) //{ // balance = rdrBalance.GetFloat(0); //} balance = float.Parse(getBalance.ExecuteScalar().ToString()); } catch { balance = 0; } myConnection.Close(); return balance; } ===============These are my codes, and it work fine, balance will has a right value, but if I comment the line "balance = float.Parse(getBalance.ExecuteScalar().ToString());"and decomment the 5 lines above, get rid of try catch, I get the error:"Specified cast is not valid"Here is the some informations when I addwatch rdrBalance-        rdrBalance    {System.Data.OleDb.OleDbDataReader}    System.Data.OleDb.OleDbDataReader+        base    {System.Dat

Invalid cast exception...


I thought I had mastered all this.. I'm testing for dbnull. This exception isn't occuring in my code. It's in some other code. What does this "strong typing exception" mean?

Imports DataSet2TableAdapters
Partial Class admin_fixdb
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim I As Integer
        Dim S1 As String
        Dim S2 As String
        Dim S3 As String
        Dim J As Integer
        Dim k As Integer
        Dim l As Integer
        Dim s4 As String
        Dim s5 As String
        Dim s6 As String

        Dim tbllinkadapter As New tblLinkTableAdapter
        Dim tbllink As DataSet2.tblLinkDataTable
        tbllink = tbllinkadapter.GetData
        For Each tbllinkrow As DataSet2.tblLinkRow In tbllink
            If Not IsDBNull(tbllinkrow.SenderLinkOn.ToString) Then
                I = tbllinkrow.SenderLinkOn.IndexOf(".")
                If tbllinkrow.SenderLinkOn.Substring(I - 1, 1) = "_" Then
                    J = Len(tbllinkrow.SenderLinkOn)
                    S1 = tbllinkrow.SenderLinkOn.Substring(0, I - 1)
                    S2 = tbllinkrow.SenderLinkOn.Substring(I, (J - I))
                    S3 = S1 + S2
                    Response.Write("Senderlinkon: " & S3)

Unable to cast COM Object - Exception


Hi everyone,

Ive been trying to develop a COM Client application, but without success. My goal is to create an application that can open reports in Cognos Impromptu. Ive got Cognos Impromptu installed on this machine and im using Visual Studio 2008 to develop the client.

I created my project as a consoleapplication in Visual Studio. Next, I added the Impromptu Client Reference via Project > Add Reference > COM. All works fine till now, Visual Studio creates my COM Wrapper dll and adds it to the bin/debug folder.

But when I trry to run my program, it gives me the following Exception:

Unable to cast COM object of type 'ImpromptuClient.ImpromptuApplicationClass' to
 interface type 'ImpromptuClient.IAppAuto'. This operation failed because the Qu
eryInterface call on the COM component for the interface with IID '{2F835754-FB4
F-11CF-8E5F-00401C60350D}' failed due to the following error: No such interface
supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).
Press any key to continue . . .

The code I use is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.

Linq2SharePoint Invalid Cast Exception


I'm trying to use Linq2SharePoint to get a count if items in a document library using the following code:


var context = new MyDataContext(webUrl);

var count = (from item in context.MyDocumentLibrary.ScopeToFolder("/", true).OfType<NewBusinessApplication>()
       where item.NewBusinessStatus = "Validation"
       select item).Count()

This should return a count of all NewBusinessApplication documents in all folders with the NewBusinessStatus of Validation.

If a run this on a document library with a mixture of document types it behaves as expected.  However, if a workflow has run on one of the NewBusinessApplication documents I get and InvalidCastException.

It appears from the stack trace that the error is when it's mapping the SPListItem to the concrete type generated by SPMetal but I can't find the specific column that's causing the issue.

Any suggestions or known issues I should look o


Every self-respected programmer should include exception handling techniques. Sometimes your application will generate an error. Regardless of who was responsible for this error, the programmer or the user, it is up to the first to include the necessary exception handling techniques to keep his/her program from crashing. The .Net environment provides useful techniques for avoiding disastrous errors such as try-catch statements and user-defined exceptions.

Global Exception Handling with ASP.NET

After your global exception handler has done its work, you'll want to redirect the users of your website to a friendly page that tells them that something has gone wrong, and then provide them with customer support information as well as a link back to your web application's home page.

SQL Server 2005 Try and Catch Exception Handling

I'm pretty excited to see that there is some real error handling for T-SQL code in SQL Server 2005. It's pretty painful to have your wonderfully architected .NET solution tainted by less-than-VBScript error handling for stored procedures in the database. The big difference being the addition of TRY..CATCH blocks. Let's take a look:

How to cast integer values as an array of enum values?


Hello all!

I'm working with VS2010 Beta2, ASP.NET and Dynamic Data. I'm using VB but will certainly be happy to receive a C# example if necessary. Laughing

I used a few of Steve's examples (Writing Attributes and Extension Methods for Dynamic Data and Dynamic Data - Hiding Columns in selected PageTemplates) to create a custom property attribute to be applied to a dynamic data column and want it to accept an array of enum values (each value will represent a dynamic data page template where this column should not be displayed).  My new attribute works fine when I hardcode it like this, meaning the HideColumnIn attribute is properly populated with the array of enum values:

<HideColumnIn(PageTemplate.List, PageTemplate.Edit)> _
Public Property My_DD_Column As Object


However, I want to store the values to be used for the HideColumnIn in the DB as integer values that correspond to the

reader.getordinal("column_may_not_exist") how to catch the exception?



would any body please help me to catch the exception if the column doesnot exist as my table columns are not static.

sometimes its throwing me indexoutofrange exception as the column doesnot exist

thanks for the help guys

Error while using exception handling block el 4.1


Hi Folks,


i am trying to use tyhe exception handling block of Enterprise library 4.1.


I just createda polisy and used IndexOutOfRangeException and added a replace handler and a logging handler to it.

I am using the NotifyRethrow PostHandlingAction to the exception.


During runtime I am getting an exception on the HandleException event, The exception is added below:



Object reference not set to an instance of an object.

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.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 42:             catch (Exception ex)
Line 43:             {
Line 44:                 bool reThrow = ExceptionPolicy.HandleException(ex, "ReplacePolicy");
Line 45:         

userprincipal.changepassword throws exception


Hi all,

      userprincipal.changepassword(oldpassword, newpassword);

gives error: that is Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. (Exception from HRESULT: 0x80070547)

but userDirectoryEntry.invoke("ChangePassword", new object[] { oldpassword, newpassword });

      userDirectoryEntry.CommitChanges works fine.

Any one please tell me the reason behind this.

active directory exception unusual behaviour


i have a small problem
i want user names from active directory for an auto completer type of service
the method is always throwing an exception 
"searcher.FindAll()' threw an exception of type 'System.DirectoryServices.DirectoryServicesCOMException' System.DirectoryServices.SearchResultCollection 

"Exception from HRESULT: 0x800AC472"


Am Exporting Data in to Excel File,meanwhile if i open any other Excel file than the excel File on which am exporting data gets opened up Automatically having name Book1.How should i stop these excel file not to get open.In the Error log i get an error message showing " Exception from HRESULT: 0x800AC472" . Need help on these.Thanks in Advance.

WebControls.TableRow throws exception on Add()


I have the following method to strip hidden and user-specified columns from a gridviewrow and return a tablerow. 

    Private Shared Function StripHiddenColumns(ByVal gvRow As GridViewRow, ByVal ColumnsToExclude() As Integer) As TableRow

        Dim row As New TableRow
        Dim i As Integer = 0
            For Each cell As TableCell In gvRow.Cells
                If cell.Visible Then
                    If Not ColumnsToExclude.Contains(i) Then
                    End If
                End If
                i += 1

            Return row
        Catch ex As Exception
            Throw ex
        End Try
    End Function

However, when I run this code and hit the Add method for the TableRow,  I get an InvalidOperationException stating the Collection was modified; enumeration operation may not execute.  I've gotten this exception before, but usually it's because I'm attempting to modify a table that is databound.  This particular one is not, i am creating it.  Can anyone offer any insight? 

Thanks in advance.


CLR Inside Out: Unhandled Exception Processing In The CLR


In this installment of CLR Inside Out Gaurav Khanna explains everything you need to know about unhandled exception processing in the .NET Framework.

Gaurav Khanna

MSDN Magazine September 2008

Enterprise Library: Take Exception To Critical Errors With Custom Application Blocks


Enterprise Library is a collection of application functionality blocks that you can re-use in your application for common functionality you'd otherwise have to write again and again. Here Jay Hilyard explains how to use them.

Jay Hilyard

MSDN Magazine September 2006

Data Points: SQL Server 2005 XML Support, Exception Handling, and More


SQL Server 2005 includes several important improvements to the Transact-SQL (T-SQL) language. One added feature is a new kind of trigger that fires when data definition language (DDL) statements run.

John Papa

MSDN Magazine May 2006

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend