使用阵列中的Repeater

时间:2012-01-17 14:51:50

标签: asp.net vb.net arrays data-binding repeater

假设我有一组逗号分隔的列表需要显示在Repeater中,我该怎么做?

所以,

List1 = "1, 2, 3, 4"
List2 = "a, b, c, d"

如果我将这些转换为数组,如何将它们绑定到Repeater并获取Repeater中每个列表的值?

我想获得一个如下所示的HTML输出:

<div>
    <span> CONTENT TO LIST 1(0) </span>
    <span> CONTENT OF LIST 2(0) </span>
</div>

<div>
    <span> CONTENT TO LIST 1(1) </span>
    <span> CONTENT OF LIST 2(1) </span>
</div>
.... etc

3 个答案:

答案 0 :(得分:4)

是的,你可以,这是一个简单的例子。

标记:

<asp:Repeater ID="rpTest" runat="server">
    <ItemTemplate>
        <div id="row<%# Eval("ID").ToString() %>">DIV CONTENT</div>
    </ItemTemplate>
</asp:Repeater>

准备测试代码:

public class TestObject
{
    public int ID { get; set; }
    public string Text { get; set; }
}

在您的Page_Load中或初始化Repeater

的位置
List<TestObject> lst = new List<TestObject>();
lst.Add(new TestObject() { ID = 0, Text = "Zero" });
lst.Add(new TestObject() { ID = 1, Text = "One" });
lst.Add(new TestObject() { ID = 2, Text = "Two" });
lst.Add(new TestObject() { ID = 3, Text = "Three" });

rpTest.DataSource = lst;
rpTest.DataBind();

输出:

<div id="row0">DIV CONTENT</div>     
<div id="row1">DIV CONTENT</div>     
<div id="row2">DIV CONTENT</div>    
<div id="row3">DIV CONTENT</div>

修改

要绑定到Array,只需将Array分配给DataSource,然后访问绑定中的Array项:

<%# Container.DataItem %>

答案 1 :(得分:0)

我有一个建议aspx:

<asp:Repeater ID="rep" runat="server">
        <ItemTemplate>
            <div>
                <span>CONTENT TO LIST 1(<%# DataBinder.Eval(Container, "DataItem.Key").ToString()%>)</span>
                <span>CONTENT TO LIST 2(<%# DataBinder.Eval(Container, "DataItem.Value").ToString()%>)</span>
            </div>
        </ItemTemplate>
    </asp:Repeater>

背后的代码:

Dim test() As String = "1,2,3,4".Split(",")
Dim test2() As String = "a,b,c,d".Split(",")

Dim ls As New List(Of KeyValuePair(Of String, String))
For i As Integer = 0 To test.Count - 1
    ls.Add(New KeyValuePair(Of String, String)(test(i), test2(i)))
Next
rep.DataSource = ls
rep.DataBind()

答案 2 :(得分:0)

<。>在.net webforms中你可以使用

<% for (int i = 0; i < totalRequired; i++)
   { %>
   <div id="<%= i %>"></div>
<% } %>

希望有所帮助。