Skip to main content

Databinding Tips: Nesting Eval Statements




Maybe this is obvious, but it wasn’t obvious to me. I’m binding some data in a GridView that has the following output based on two numeric columns in my database. It doesn’t matter why or what the data represents. It’s just two pieces of data with some formatting:

int, (string) Basically these are two measurements. Initially, I would databind this like so

Basically these are two measurements. Initially, I would databind this like so:

<%# Eval("First") %>, (<%# Eval("Second") %>)

The problem with this is that if the first field is null, I’m left with this output.

, (string

Ok, easy enough to fix using a format string:

<%# Eval("First", "{0}, ") %>(<%# Eval("Second") %>)

But now I’ve learned that if the first value is null, the second one should be blank as well.


<%# Eval("First", "{0}, " + Eval("Second", "({0})")) %>


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataBind.aspx.cs" Inherits="DataBind" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="Server" Text='<%# Eval("First", "{0}, " + Eval("Second", "({0})")) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl3" runat="Server" Text='<%# Eval("First") %>, (<%# Eval("Second") %>)'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>





using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class DataBind : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = GetDataSet();
GridView1.DataBind();

}

}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("First", typeof(Int32)));
dt.Columns.Add(new DataColumn("Second", typeof(string)));
for (int i = 0; i <= 10; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);

}
for (int i = 11; i <= 15; i++)
{
dr = dt.NewRow();
dr[0] = i;

dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}
return dt;
}
}

Comments

Popular posts from this blog