如何在Repeater中获取文字内容值

时间:2012-08-06 08:46:00

标签: c# asp.net .net repeater

我有一个转发器,如下所示。如何在代码中获取报告ID(来自hiddenContent2中的表达式)?

表达式是

<%# Eval("ReportID") %>

注意:我更喜欢使用“FindControl”的方法。

ASP.NET

<asp:Repeater ID="rptReports" runat="server">
    <HeaderTemplate>
        <div></div>
    </HeaderTemplate>
    <ItemTemplate>
        <div id="repeaterIdentifier" class="repeaterIdentifier">
            <div id="reportTitle" class="reportTitle">
                <%# Eval("Title") +":" %>
            </div>
            <div id ="reportFrequency" class="reportFrequency">
                <%# " Frequency - "+ Eval("Frequeny") %>
            </div>
        </div>

        <div class="reportContent">
            <div class="repeaterLine">
                <asp:TextBox ID="txtEmailRecipients" runat="server" class="textEdit" Text='<%# Eval("Recipients")%>' TextMode="MultiLine"></asp:TextBox>
            </div>
        </div>

        <div id="hiddenContent2"> 
             <%# Eval("ReportID") %>
        </div>
    </ItemTemplate>
</asp:Repeater>

背后的代码

protected void Save_Click(object sender, EventArgs e)
{
    foreach (RepeaterItem item in rptReports.Items)
    {
        foreach(Control c in item.Controls)
        {
            string test1 = c.ID;
            Type t = c.GetType();
        }
        string emails = ((TextBox)item.Controls[1]).Text;
    }
}

2 个答案:

答案 0 :(得分:6)

试试这个,

foreach (RepeaterItem item in rptReports.Items)
{
    Label lblReportID= (Label)item.FindControl("lblReportID");
    string ReportID = lblReportID.Text;
}

如果您使用的是“div”,请尝试以下操作:

 <div id="hiddenContent2" runat="server"> 
        <%# Eval("ReportID") %>
 </div>

 foreach (RepeaterItem item in rptReports.Items)
 {
     System.Web.UI.HtmlControls.HtmlGenericControl hiddenContent2 = (System.Web.UI.HtmlControls.HtmlGenericControl)item.FindControl("hiddenContent2");
     string ReportID = hiddenContent2.InnerHtml;
 }

答案 1 :(得分:2)

您可以使用Repeater的ItemIndex属性。这是样本:

<asp:Repeater runat="server" ID="repTest">
    <ItemTemplate>
        <div id="hDiv">
            <%# Eval("SomeID") %>
        </div>
    </ItemTemplate>
</asp:Repeater>

代码behinde:

protected void Page_Load(object sender, EventArgs e)
{
    var objects =
        new object[] {
            new {SomeID = 1},
            new {SomeID = 2},
            new {SomeID = 3},
            new {SomeID = 4}
        };

    repTest.DataSource = objects;
    repTest.DataBind();
}

protected void btnClick(object sender, EventArgs e)
{
    var data = (object[])repTest.DataSource;
    foreach (RepeaterItem item in repTest.Items)
    {
        var obj = data[item.ItemIndex];
        var id = obj.GetType().GetProperty("SomeID").GetValue(obj, null);
    }
}

所以,你需要做两件事。

  • 将DataSource转换为您的类型。 (我只使用object []作为样本。)
  • 将数据[item.ItemIndex]投射到您的类型。我只是使用反射,因为我有anonimus类型,所以如果你有一个类型,你可以投射它。