novacara
novacara

Reputation: 2257

New to <%# - weird error

I'm using a TemplateField to add an extra "calculated" column to a gridview that is bound to a table in a database. I'm getting this weird error and I have no clue how to begin to debug it. I might be doing something wrong/non-doable with the <%# syntax and if so please let me know what. I don't fully understand it.

Code:

<asp:TemplateField>
    <ItemTemplate>
    <asp:Label runat="server" Text='<%# Math.Round(decimal.Parse((((int.Parse(Eval("Num1").ToString())) * 36) / (235 * int.Parse(Eval("Num2").ToString()))).ToString()), 0); %>'></asp:Label>
    </ItemTemplate>
</asp:TemplateField>

Error: CS1525: Invalid expression term ','

There is a comma...but its for the second argument of Math.Round. Or am I doing something that is not do-able in this way? Also, the Math.Round line doesn't indicate any errors in the code-behind (my parenthesis should be good).

Upvotes: 1

Views: 186

Answers (3)

Narnian
Narnian

Reputation: 3908

It looked alright for me. However, it does seem like a fairly confusing line of text. If Num1 and Num2 are columns in your database, then you can just add a property on the class that represents the table.

So, next to where Num1 and Num2 are defined, define another property--not representing a column in the database, but a computation of values in the database.

This removes the computation from one specific page, so if you have to use it again somewhere, you can just reference the property.

Alternatively, you could reference a method on your code behind...

<%# GetComputedValue((int)Eval("Num1"), (int)Eval("Num2")) %>

protected string GetComputedValue(int num1, int num2)

I like the property idea better, though, since it is reusable.

Upvotes: 1

bechbd
bechbd

Reputation: 6341

If you really need the ability to do the rounding etc just create a public function in your code behind that is called Round and call that from the data binding expression(s). That way you don't have any issues with a comma as well as having all your logic in one place so it is easier to maintain consistency later on.

Upvotes: 2

Mark Brackett
Mark Brackett

Reputation: 85655

In an databind expression, you're limited to a single statement. Drop the ";". I'll trust the statement itself is well-formed.

Upvotes: 6

Related Questions