add string item to datalist asp.net

2019-07-18 14:14发布

问题:

I am working with DataList in asp.net C#. I want to add strings as an item to datalist. I do this by following code:

      ArrayList al = new ArrayList();

      for (int i = 0; i < 2; i++) {
          al.Add(i.toString());
      }

      DataList2.DataSource = al;
      DataList2.DataBind();

But when I run the program I cannot see the numbers 0 and 1. Instead I see following picture as datalist:

Where is my numbers? Does someone know any solution? Note that the task is to add to the datalist the array of string.

The datalist code is:

<asp:DataList ID="DataList2" runat="server" BackColor="White" 
                     BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" CellPadding="4" 
                     GridLines="Both">
                     <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
                     <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
                     <ItemStyle BackColor="White" ForeColor="#330099" />
                     <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
                 </asp:DataList>

Moreover, is it possible to add scroll to the datalist?

回答1:

Add to your DataList an ItemTemplate as below:

<ItemTemplate>
     <%# Container.DataItem %>
</ItemTemplate>


回答2:

You need to add an ItemTemplate

<asp:DataList ID="DataList2" runat="server" BackColor="White" BorderColor="#CC9966"
    BorderStyle="None" BorderWidth="1px" CellPadding="4" GridLines="Both">
    <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
    <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
    <ItemStyle BackColor="White" ForeColor="#330099" />
    <SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
    <itemtemplate><%# Container.DataItem %></itemtemplate>
</asp:DataList>