Friday, March 17, 2017

Handle GridView TemplateFields null values in aspx markup

Hello,
To handle null values in GridView TemplateFields through aspx/html markup rather than code-behind, you can simply use the language operators to those fields. One approach is to use the conditional ternary operator in C# and VB.NET. The sample codes below illustrates how to do in C# and VB.NET. For C#, use the (?) operator. While VB.NET uses If() operator.
C#.NET Code
 <asp:TemplateField HeaderText="Name" SortExpression="EmpName">
 <ItemTemplate>
    <asp:Label ID="lbl" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:TextBox ID="txtEmployee" runat="server" Text='<%# Eval("EmpName") == System.DBNull.Value ? string.Empty : Eval("EmpName").ToString() %>' ></asp:TextBox>
 </EditItemTemplate>
</asp:TemplateField>
    
VB.NET Code
<asp:TemplateField HeaderText="Name" SortExpression="EmpName">
 <ItemTemplate>
    <asp:Label ID="lbl" runat="server" Text='<%# Eval("EmpName") %>'></asp:Label>
 </ItemTemplate>
 <EditItemTemplate>
  <asp:TextBox ID="txtEmployee" runat="server" Text='<%# If(IsDBNull(Eval("EmpName")), String.Empty, Eval("EmpName").ToString())%>' ></asp:TextBox>
 </EditItemTemplate>
</asp:TemplateField>

Cheers! :-)

0 comments:

Post a Comment