在Repeater控件中访问文本框

Jas*_*son 24 c# asp.net textbox repeater

我能想到的所有方式看起来都非常苛刻.这样做的正确方法是什么,或者至少是最常见的?

我正在从LINQ-to-SQL查询中检索一组图像,并将它和一些其他数据数据绑定到转发器.我需要在转发器中为每个项添加一个文本框,让用户更改每个图像的标题,与Flickr非常相似.

如何访问转发器控件中的文本框并知道该文本框属于哪个图像?

以下是转发器控件的外观,使用提交按钮更新Linq-to-SQL中的所有图像行:

替代文字http://casonclagg.com/layout.jpg

编辑:

这段代码有效

只要确保你不要像我一样在if(!Page.IsPostBack)之外绑定你的价值.哎呀.

<asp:Repeater ID="Repeater1" runat="server">
    <ItemTemplate>
        <div class="itemBox">
            <div class="imgclass">
                <a title='<%# Eval("Name") %>' href='<%# Eval("Path") %>' rel="gallery">
                    <img alt='<%# Eval("Name") %>' src='<%# Eval("Path") %>' width="260" />
                </a>
            </div>
            <asp:TextBox ID="TextBox1" Width="230px" runat="server"></asp:TextBox>
        </div>
    </ItemTemplate>
</asp:Repeater>
Run Code Online (Sandbox Code Playgroud)

并提交点击:

protected void Button1_Click(object sender, EventArgs e)
{
    foreach (RepeaterItem item in Repeater1.Items)
    {
        TextBox txtName = (TextBox)item.FindControl("TextBox1");
        if (txtName != null)
        {
            string val = txtName.Text;
            //do something with val
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Ash*_*pta 34

您是否在点击按钮时尝试了以下内容: -

foreach (RepeaterItem item in Repeater1.Items)
{
      TextBox txtName= (TextBox)item.FindControl("txtName");
      if(txtName!=null)
      {
      //do something with txtName.Text
      }
      Image img= (Image)item.FindControl("Img");
      if(img!=null)
      {
      //do something with img
      }
}
Run Code Online (Sandbox Code Playgroud)

/*其中txtName和Img分别是转发器中文本框的ID和图像控件.*/

希望这可以帮助.

  • 没关系,我是个白痴.我的页面加载中没有if(!Page.IsPostback).所以文本框正在重置.忽略一切.= d (3认同)

Eti*_*uis 12

的.aspx

        <asp:Repeater ID="rpt" runat="server" EnableViewState="False">
        <ItemTemplate>
                <asp:TextBox ID="txtQty" runat="server" /> 
        </ItemTemplate>
        </asp:Repeater>
Run Code Online (Sandbox Code Playgroud)

的.cs

        foreach (RepeaterItem rptItem in rpt.Items)
        {
            TextBox txtQty = (TextBox)rptItem.FindControl("txtQty");
            if (txtQty != null) { Response.Write(txtQty.Text); }          
        }
Run Code Online (Sandbox Code Playgroud)

确保将EnableViewState ="False"添加到转发器,否则将获得空字符串.(这浪费了我的时间,不要浪费你的:))

  • 提及EnableViewState的+1 (3认同)