Cast from type 'DBNull' to type 'String' is not valid.
I have seen this question many times in the ASP.NET forums and thought that it would be a good idea to blog about.
When you are working with functions in the HTML of your DataGrid and passing the value (which can be also NULL) from the database to a function, which accepts a string, then you will get such an error.
Cast from type 'DBNull' to type 'String' is not valid.
To get this working you will have to pass the value as an object. That means the function must simply accept it as an object instead of a string. Something like this:
<asp:datagrid id="datagrid".....>
<Columns>
<asp:TemplateColumn ...>
<ItemTemplate>
<%# DoSomething(Container.DataItem("TheValue")) %>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:datagrid>
And in your Codebehind:
function public DoSomething(Dim obj as Object)
If not IsDBNull(obj) then
' Do the processing here...
End If
end function
Sonu