Friday, August 27, 2010

ASP.NET and the annoying DropDownList problem...

'ddlxxxxx' has a SelectedValue which is invalid because it does not exist in the list of items.

Many people complain about this untrappable error, but if you search hard enough, you will eventually find the fix: http://forums.devx.com/showthread.php?t=155180


So, it turns out that it's very easy to create your own DropDownList control inheriting all the behaviour of the original except this error.  Now, if the value in your database doesn't match one of the values in the pull-down it will display the default value (1st in the list) - rather more friendly behaviour.  There's much more about this at http://aspddlsucks.spaces.live.com/ - I think it's annoying that a failure to enforce referential integrity in your database is punished in such a brutal way, so that you can't even catch the violation in a try/catch in your application code.  The official Microsoft response is certainly patronising: "just make sure your data is always correct".

1. Using Visual Basic 2008 Express (or similar, I'm sure C#-ers can work it out), compile the following code as a Class (be sure to add a reference to 'System.Web')

Imports Microsoft.VisualBasic
Imports System.Web

Namespace FixedDDL
    Public Class DropDownList
        Inherits System.Web.UI.WebControls.DropDownList

        Protected Overrides Sub PerformDataBinding(ByVal dataSource As System.Collections.IEnumerable)
            Try
                MyBase.PerformDataBinding(dataSource)
            Catch OutOfRangeEx As System.ArgumentOutOfRangeException
                ' Ignore exception
            End Try
        End Sub

    End Class
End Namespace

2. Grab the FixedDDL.dll and put it in the Bin directory of your web application

3. Add the following lines into your web.config:
<system.web>
<pages>
<tagMapping>
<add mappedTagType="FixedDDL.FixedDDL.DropDownList" tagType="System.Web.UI.WebControls.DropDownList">
</add>
</tagMapping>
</pages>

...
</system.web>





4. Job done

No comments:

Post a Comment