Thursday, August 26, 2010

NULL In GridView EVAL Calling Serverside Method In ItemTemplate

My Table in database look like as shown in image below, some columns contains NULL values and i'll be showing "No Records Found" instead of NULL values in GridView.

To achieve this i've written a Method in code behind and will be calling this method in ItemTemplate of GridView. 


Html source of GridView 



<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false">
<Columns>
<asp:BoundField ShowHeader="true" DataField="ID" 
                              HeaderText="ID" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Name")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" 
           Text='<%# CheckNull(Eval("Location")) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT ID, Name, Location FROM Details">
</asp:SqlDataSource>

C# code for the CheckNull method



protected string CheckNull(object objGrid)
    {
        if (object.ReferenceEquals(objGrid, DBNull.Value))
        {
            return "No Record Found";
        }
        else
        {
            return objGrid.ToString();
        }
     }
VB.NET code behind

Protected Function CheckNull(ByVal objGrid As Object) As String
    If Object.ReferenceEquals(objGrid, DBNull.Value) Then
        Return "No Record Found"
    Else
        Return objGrid.ToString()
    End If
End Function

No comments: