Check for null on gridview template column

Posted on 2007-10-16
Last Modified: 2013-11-26
How can I check for NULL in the following templatefield of a gridview?  I am using a dynamic search and if nothing is returned I get error.

Here is the code

                <asp:TemplateField HeaderText="Username">
                    <asp:HyperLink ID="hlUrl" runat="server" NavigateUrl='<%# FormatUrl( (String) Eval("UserName") ) %>'
                        Text='<%# Eval("Username") %>' />                    
Question by:mugsey

    Author Comment

    Oops here is the error

    Unable to cast object of type 'System.DBNull' to type 'System.String'.
    LVL 96

    Expert Comment

    by:Bob Learned
    Try this instead:

         FormatUrl( Eval("UserName").ToString() )

    LVL 7

    Accepted Solution


      if (!(Convert.IsDBNull(DataBinder.Eval(e.Row.DataItem, "UserName"))))
        string _username = DataBinder.Eval(e.Row.DataItem, "UserName").ToString();


    Featured Post

    Threat Intelligence Starter Resources

    Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

    Join & Write a Comment

    Suggested Solutions

    Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
    Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
    Need more eyes on your posted question? Go ahead and follow the quick steps in this video to learn how to Request Attention to your question. *Log into your Experts Exchange account *Find the question you want to Request Attention for *Go to the e…
    Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

    729 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

    19 Experts available now in Live!

    Get 1:1 Help Now