maxp
maxp

Reputation: 25141

Manipulate databound values in databound control? ASP.NET Webforms

I'm working on the following markup, inside a DataBound control in ASP.NET Webforms.

<asp:TemplateField HeaderText="DomainID">
    <ItemTemplate>
        <%  for (int i = 0; i < 10; i++)
            {%>
            <%#Eval("DomainID"); %>
            <%  ++i;
            } %>
        </ItemTemplate>
</asp:TemplateField>

Is it possible to actually write code blocks inside the <%#Eval("DomainID"); %> section such as:

<%# var x = Eval("DomainID"); if ((int)x)>0){//print this}   %>

Upvotes: 2

Views: 779

Answers (1)

Kelsey
Kelsey

Reputation: 47726

When it starts getting this complicated I always recommend changing your structure to use a server side control and do the binding via the OnDataBinding event for that control.

Example:

<asp:TemplateField HeaderText="DomainID"> 
    <ItemTemplate> 
        <asp:Literal ID="ltDomainID" runat="server" 
            OnDataBinding="ltDomainID_DataBinding" />
    </ItemTemplate>

Then in your codebind implement the OnDataBinding:

protected void ltDomainID_DataBinding(object sender, System.EventArgs e)
{
    Literal lt = (Literal)(sender);
    for (int i = 0; i < 10; i++) 
    {
        var x = (int)(Eval("DomainID"));
        if (x > 0)
        {
            lt.Text += x.ToString();
        }
        ++i; 
    }
}

I might have your logic a little messed up but this should give you the basic idea. Implementing the logic server side keeps you aspx much cleaner and it ties the logic directly to the output control (which in this case is the Literal).

Upvotes: 2

Related Questions