Complex data binding expressions in ASP.NET

Onion Blog

Syndication

I often find when using templated data-bound controls (in either ASP.NET 1.1 or 2.0) that my expressions become rather difficult to understand because of the need to fit all of your logic into a single expression. For example, I have seen databound expressions that look something like:
 
<asp:TemplateField HeaderText="SomeColumn">
  <ItemTemplate>
    <%# ((bool)Eval("foo")) ? Eval("bar") : (((bool)Eval("quux")) ? Eval("a") : Eval("b")) %>
  </ItemTemplate>
</asp:TemplateField>
 
Which is even worse in 1.1 because each Eval must be replaced with DataBinder.Eval(Container.DataItem, "xx"). There are also occasions where you just can't compress all the logic you need to into a single expression. An alternative, which I find myself using quite a bit, even when developing in 2.0, is to write a single method in your code behind class to generate the desired string. Have it take an object reference (which will be the bound row) and take as many lines as you like to construct the string to be generated in the template. Here's a method that returns the same string as the overly-complex expression above:
 
protected string GenerateFooString(object dataItem)
{
  bool foo = (bool)DataBinder.Eval(dataItem, "foo");
  bool quux = (bool)DataBinder.Eval(dataItem, "quux");
  string ret = string.Empty;
  if (foo)
    ret = (string)DataBinder.Eval(dataItem, "bar");
  else if (quux)
    ret = (string)DataBinder.Eval(dataItem, "a");
  else
    ret = (string)DataBinder.Eval(dataItem, "b");
 
  return ret;
}
 
And the simplified template now looks like:
 
<asp:TemplateField HeaderText="SomeColumn">
  <ItemTemplate>
    <%# GenerateFooString(Container.DataItem) %>
  </ItemTemplate>
</asp:TemplateField>
 
 

Posted Dec 16 2005, 07:43 AM by fritz-onion
Filed under:

Comments

Andrew Robinson wrote re: Complex data binding expressions in ASP.NET
on 12-16-2005 8:46 AM
Fritz,

what are the pros / cons of not referencing the dataItem in your method and Eval? This seems to work fine and I use it quite a bit.

Thanks,

>>>>

asp:Label ID="LabelShifts" runat="server" Text='<%# GetShifts() %>'

protected string GetShifts()
{
string day = (bool)Eval("PostingDay") ? "Day " : string.Empty;
string swing = (bool)Eval("PostingSwing") ? "Swing " : string.Empty;
string grave = (bool)Eval("PostingGrave") ? "Grave" : string.Empty;

if (day.Length > 0 && swing.Length > 0 && grave.Length > 0)
{
return "All";
}

return day + swing + grave;
}
Fritz Onion wrote re: Complex data binding expressions in ASP.NET
on 12-16-2005 9:00 AM
Calling Eval directly is fine, and even recommended in 2.0, so you're right there's no need to pass the data item.

The code I showed works in 1.1 as well as 2.0, which is why I left it taking a dataItem as a parameter.
Sergio Pereira wrote re: Complex data binding expressions in ASP.NET
on 12-16-2005 9:21 AM
That's a nice trick, especially in 1.x. I'd suggest putting the function inside a <script runat=server> block in the ASPX/ASCX file itself instead of creating it in the code-behind.
Todd Taylor's Rambling wrote Complex Data Binding Expressions
on 12-17-2005 12:52 PM
Anatoly Lubarsky wrote re: Complex data binding expressions in ASP.NET
on 12-17-2005 1:23 PM
May be it is good for demo apps.
In real life I will have a class entity behind the control to bind to. I can create properties, functions, etc.
khuzema wrote re: Complex data binding expressions in ASP.NET
on 12-17-2005 10:55 PM
This is really helpful.
Israel Aece wrote re: Complex data binding expressions in ASP.NET
on 12-18-2005 4:27 AM
Hello Fritz,

Couldn't you create the logic of GenerateFooString method in the RowDataBound event instead of creating one method auxiliary?

Att,
Fritz Onion wrote re: Complex data binding expressions in ASP.NET
on 12-18-2005 4:45 AM
Sure, you could handle the RowDataBound event and do it all in code. The difference is that using the <%# %> syntax, it is much more convenient and intuitive where the string will be placed. Doing it from code means you have to traverse the object model to find the control to modify. Using <%# %> also means that it is easy to intersperse static layout with dynamically bound expressions.
The road to C# master trapemiya wrote Complex data binding expressions in ASP.NET
on 12-19-2005 12:07 AM
Complex data binding expressions in ASP.NET
Leo wrote re: Complex data binding expressions in ASP.NET
on 12-21-2005 11:56 AM
Do you have to make sure you do a Page.DataBind() for the binding expressions to occur?
Technical Notes wrote ASP.NET Links, Resources and How Tos via Scott Guthrie
on 12-27-2005 7:03 AM
For those looking to stay abreast of ASP.NET development, I highly recommend following Scott Guthrie's...
Oliver wrote re: Complex data binding expressions in ASP.NET
on 01-03-2006 11:50 AM
Does anybody know how if is it posible to handle complex expressions or maybe create a function call in skin file (Theme).

I have this sample in my skin file

<asp:Label runat="server" SkinID="test" Text='<%# GetValue() %>' Font-Bold="true" />

parser give an error : Code blocks are not allowed in this file.

Please help!!!
Mark wrote re: Complex data binding expressions in ASP.NET
on 02-06-2006 11:46 AM
Fritz,
I've used the same approach, but have been wondering how to do this in a control that is not a data control. Take for example a TextBox or Label control out there on the page - by itself - not "wrapped" within a Data control (such as a FormView). There are plenty of times that I want controls on my page to be databound, but do not want to be forced to use a FormView, GridView, etc. I just want to hook the control up to some data for display. Now, I have to roll my own code within the Page_Load event (or somewhere else, depending).
anjee wrote re: Complex data binding expressions in ASP.NET
on 03-14-2006 4:11 PM
Thanks, helped me a lot.
cam wrote java script
on 03-16-2006 9:01 AM
Fritz, I've watch you webevents and thank you.... my problem:
on delete in gridview I need to warn my user of the concequence.
in the old way i captured the listitemtype and set the attributes...

in 2.0 it's not the same....
would you be kind enough to have a sample that would help me? thanks
Fritz Onion wrote re: Complex data binding expressions in ASP.NET
on 03-22-2006 11:15 AM
This question comes up quite a bit, so I've posted a blog entry on the topic:
http://www.pluralsight.com/blogs/fritz/archive/2006/03/22/20514.aspx
Simone Busoli Weblog wrote Espressioni di DataBinding complesse con ASP.NET
on 03-25-2006 4:11 PM
Peter wrote re: Complex data binding expressions in ASP.NET
on 03-26-2006 11:56 AM
Great post, do you know if i can use this method to make a datalist do something different based on a condition?
For example display a list of items which have sub headings in them when a column in the datatable that its bound to changes?
e.g.

Heading1
some stuff
some more stuff
Heading2
some other stuff
something else

The data behind would look like

some stuff, Heading1
some more stuff, Heading1
some other stuff, Heading2
something else, Heading2

Thanks in advance.
Code obsessed wrote Reading list for April
on 04-07-2006 1:44 AM
The Eagle wrote re: Complex data binding expressions in ASP.NET
on 05-01-2006 10:41 AM
Hi..
What about Container.ItemIndex..I mean could i write:
protected string GenerateFooString(object dataItem,object itemIndex)

and:

<%# GenerateFooString(Container.DataItem,Container.ItemIndex) %>
The Eagle wrote re: Complex data binding expressions in ASP.NET
on 05-01-2006 11:30 PM
if any one could answer my question above please send it to my email :
nabeel@engineeringprojects.net
Ben wrote re: Complex data binding expressions in ASP.NET
on 08-15-2006 10:57 PM
Sweet finally something that worked.
Archana wrote re: Complex data binding expressions in ASP.NET
on 09-09-2006 1:23 AM
it works
Ram Pratap wrote re: Complex data binding expressions in ASP.NET
on 09-15-2006 7:15 AM
Hi!

I need the code to add template columns to the datagrid depending on the table.

Pl, do help

Thanks in advance
Ram
Dave wrote re: Complex data binding expressions in ASP.NET
on 12-08-2006 7:29 AM
Thanks. This helped me out a ton.
Putri wrote re: Complex data binding expressions in ASP.NET
on 07-09-2007 7:15 PM
hey guys, can you help me?
how to solve this problem?
thanks


Line 78: <!-- expression to retrieve the connection string value -->
Line 79: <!-- from the Web.config file. -->
Line 80: <asp:sqldatasource id="putri"
Line 81: selectcommand="Select [HW_ID], [Title] From [tblHomework] where ([HW_ID]='<%# Bind("HW_ID") %>' )"
Line 82: updatecommand="Update [tblHomework] Set [title]=@title Where [HW_ID]=@HW_ID"


Putri wrote re: Complex data binding expressions in ASP.NET
on 07-09-2007 7:18 PM
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: The server tag is not well formed.

Source Error:
Putri wrote re: Complex data binding expressions in ASP.NET
on 07-09-2007 8:50 PM
and do you know how to make query from two databases? (sql server 2000)
thanks
Chuck Muziani wrote re: Complex data binding expressions in ASP.NET
on 07-31-2007 11:46 AM
Replace the double-quotes with single-quotes around "HD_ID" at the end of line 81...

Line 81: selectcommand="Select [HW_ID], [Title] From [tblHomework] where ([HW_ID]='<%# Bind("HW_ID") %>' )"

Should be:

Line 81: selectcommand="Select [HW_ID], [Title] From [tblHomework] where ([HW_ID]='<%# Bind('HW_ID') %>' )"
Valentina wrote re: Complex data binding expressions in ASP.NET
on 08-24-2007 4:20 PM
Another solution to this problem(on a top) gave me the same result. This is the solution:

You write User Defined Function:

create function ternary(@val1 int,@val2 varchar(100), @val3 varchar(100))
returns varchar(100)
as
begin
if @val1=0 begin
return @val3
end
return @val2
end

Stored Procedure:

create procedure gettest
as
select dbo.ternary(foo,bar,dbo.ternary(quux,a,b)) as result
from dbo.test

And template :
<ItemTemplate>
<%# Eval("result") %>
</ItemTemplate>
Chris Henry wrote re: Complex data binding expressions in ASP.NET
on 01-28-2008 6:34 AM
I used to like JSP better, but now ASP.NET 2.0 kicks JSP's BUTT!!!
www upescorts com wrote www upescorts com
on 07-09-2008 8:39 AM

Pingback from  www upescorts com

Add a Comment

(required)  
(optional)
(required)  
Remember Me?