Monday, June 25, 2012

NULL In GridView EVAL Calling ServerSide Method In ItemTemplate

This example explains how to handle NULL In GridView EVAL Calling Serverside Method In ItemTemplate

In this example i am going to describe how to handle NULL values from DataBase in Eval method of GridView ItemTemplate or How to call Server side method written in code behind in ItemTemplate of GridView.

Handle NULL In GridView

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>

In above code i am calling server side method CheckNull written in code behind from ItemTemplate of GridView which check the NULL values and change it as we want.
C# code for the CheckNull method
01protected string CheckNull(object objGrid)
02    {
03        if (object.ReferenceEquals(objGrid, DBNull.Value))
04        {
05            return "No Record Found";
06        }
07        else
08        {
09            return objGrid.ToString();
10        }
11     }
VB.NET code behind
1Protected Function CheckNull(ByVal objGrid As Object) As String
2    If Object.ReferenceEquals(objGrid, DBNull.Value) Then
3        Return "No Record Found"
4    Else
5        Return objGrid.ToString()
6    End If
7End Function

And this is how gridview will render

Hope this helps

If you are searching life partner. your searching end with now offer free matrimonial website which offer free message, free chat, free view contact information. so register here : Free matrimonial website