【问题标题】:Server controls in an asp.net repeaterasp.net 中继器中的服务器控件
【发布时间】:2010-11-14 12:44:41
【问题描述】:

好像我在这里撞到了一堵墙。我希望将一些数据源绑定到 asp.net 中继器(嗯,不一定是中继器,但似乎这就是我想要的)。现在,问题来了:我还需要中继器内部的一些服务器控件来更新数据(文本框和按钮)。

据我了解,这真的不可能有条不紊地进行吗?我不能只在 itemtemplate 中添加一个文本框,然后稍后在代码隐藏中获取它。至少不容易。是否有任何已知技术可以解决此类问题?

我不能使用gridview,因为数据需要以某种方式格式化。

【问题讨论】:

    标签: asp.net repeater servercontrols


    【解决方案1】:

    如果您不想使用 ItemCommand 并且只想循环遍历 Repeater 的项目集合,因此在页面底部有一个“保存”按钮,您可以这样做:

    foreach(RepeaterItem itm in MyRepeater.Items)
    {
         TextBox t = (TextBox)(itm.FindControl("TextBox1"));
         // do something with it.
    
    }
    

    当然,您需要确保 ASPX 中的 TextBox1 具有 Runat="Server" 属性。

    【讨论】:

      【解决方案2】:

      您可以使用Repeater.ItemDataBound Event 定位嵌套在中继器中的控件。

      <asp:Repeater ID="Repeater1" Runat="server" OnItemDataBound="Repeater1_ItemDataBound">
         <ItemTemplate>
            <div><asp:TextBox ID="TextBox1" runat="server" /></div>
         </ItemTemplate>
      </asp:Repeater>
      

      然后在后面的代码中:

      protected void Repeater1_ItemDataBound(object source, RepeaterCommandEventArgs e)
      {
         if (e.Item.ItemType != ListItemType.Item && e.Item.ItemType !=
            ListItemType.AlternatingItem)
            return;
      
         TextBox textBox1 = e.Item.FindControl("TextBox1") as TextBox;
         if (textBox1 != null)
         {
         // do something with it
         }
      }
      

      【讨论】:

      • 已经试过了。没用 :( 似乎 ItemDataBound 事件发生在按钮被渲染和添加之前?无论如何, textBox1 对我来说是空的。顺便说一句;事件参数类型是 RepeaterItemEventArgs :)
      • 我相信你会想要添加一个按钮并使用 RepeaterItemCommand 事件处理程序,而不是使用 ItemDataBound。
      【解决方案3】:

      看来我的问题出在我的想法上 :)

      我的解决方案: 我只是像往常一样添加了控件,但在 ItemTemplate 中。关于控件的回调事件,我会选择:

      (按钮示例)

      protected void btnUpdate_OnClick(object sender, EventArgs e)
          {
              Button b = sender as Button;
              if (b != null)
              {
                  RepeaterItem ri = b.Parent as RepeaterItem;
                  if (ri != null)
                  {
                      string name = null;
      
                      //Fetch data
                      TextBox txtName = ri.FindControl("txtName") as TextBox;
      

      .. 等等..

      所以,在找到RepeaterItem 之后,我只是像对待任何ControlGroup 一样对待它。没关系,我实际上有 5 个不同的 textboss,用 ID="txtName" 编码,因为 asp.net 会自动在客户端标记中为控件提供“混淆”名称,并在回发时将其转换回我的 ID。

      希望这对某人有所帮助,很抱歉打扰:)

      【讨论】:

        猜你喜欢
        • 2012-07-12
        • 1970-01-01
        • 1970-01-01
        • 2013-03-07
        • 1970-01-01
        • 1970-01-01
        • 2011-03-02
        • 1970-01-01
        • 2015-11-21
        相关资源
        最近更新 更多