Sanjeewa Sanjeewa - 2 months ago 14
ASP.NET (C#) Question

<a > tag dynamically text generation issue

I have a code which I want to dynamically generate the text by using a foreach class type property value

but when ever I run it, generates a compile time error

Refer the code segment below.

<ul class="nav nav-pills nav-stacked">
<%
List<CodeCamper.EntityLayer.Transaction.SessionVO> y = new List<CodeCamper.EntityLayer.Transaction.SessionVO>();

CodeCamper.EntityLayer.Transaction.SessionVO x = new CodeCamper.EntityLayer.Transaction.SessionVO();
x.SessionTimeSlot = "Day 01";
y.Add(x);

x = new CodeCamper.EntityLayer.Transaction.SessionVO();
x.SessionTimeSlot = "Day 02";
y.Add(x);

x = new CodeCamper.EntityLayer.Transaction.SessionVO();
x.SessionTimeSlot = "Day 03";
y.Add(x);


foreach (CodeCamper.EntityLayer.Transaction.SessionVO s in y)
{
%>
<li class="active"><a href="#" runat="server" onserverclick="sample_Click"><%= s.SessionTimeSlot %></a></li>
<%
}
%>

<%-- <li class="active"><a href="#">Home</a></li>
<li class="active"><a href="#">sfsfs</a></li>--%>
</ul>


The compile time error is
Compiler Error Message: CS0103: The name 'item' does not exist in the current context


Hope for a correction of this code

enter image description here

Answer

I believe <%= s.SessionTimeSlot %> is your problem. You should use a Repeater for this purpose.

Try something like this:

<asp:Repeater ID="SessionVORepeater" runat="server">
    <ItemTemplate>
        <li class="active"><a href="#" runat="server" onserverclick="sample_Click"><%# DataBinder.Eval(Container.DataItem, "SessionTimeSlot") %></a></li>
    </ItemTemplate>
</asp:Repeater>

and in code behind (Page_Load for example):

                        List<CodeCamper.EntityLayer.Transaction.SessionVO> y = new List<CodeCamper.EntityLayer.Transaction.SessionVO>();

                        CodeCamper.EntityLayer.Transaction.SessionVO x = new CodeCamper.EntityLayer.Transaction.SessionVO();
                        x.SessionTimeSlot = "Day 01";
                       y.Add(x);

                       x = new CodeCamper.EntityLayer.Transaction.SessionVO();
                       x.SessionTimeSlot = "Day 02";
                       y.Add(x);

                       x = new CodeCamper.EntityLayer.Transaction.SessionVO();
                       x.SessionTimeSlot = "Day 03";
                       y.Add(x);

                       SessionVORepeater.DataSource = y;
                       SessionVORepeater.DataBind();

Hope this helps