C#通过Repeater中的CommandArgument传递文本框内容

时间:2011-06-20 15:10:21

标签: c# asp.net repeater commandargument

<asp:Repeater ID="Cartridges" runat="server" onitemcommand="Cartridges_ItemCommand">
    <ItemTemplate>
        <p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
        <hr class="hr4" /> 
        <p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
        <div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" CommandArgument=<%#Eval("cartID") %> Text="Buy"></asp:LinkButton></div>
   </ItemTemplate>
</asp:Repeater>

如何在CommandArgument中传递文本框值?对不起完全失去了......

3 个答案:

答案 0 :(得分:3)

您尝试过:CommandArgument='<%#Eval("cartID") %>'

这与你的不同,因为它被单引号包围,我想这是正确的语法。

答案 1 :(得分:2)

使用FindControl获取转发器项目中的其他项目。例如:

 protected void repeater_ItemCommand(object sender, RepeaterCommandEventArgs e)
 {
      LinkButton lb = (LinkButton)e.CommandSource;
      string textBoxValue = ((TextBox)lb.Parent.FindControl("cartQty")).Text;         
 }

答案 2 :(得分:0)

你需要将cartId绑定到linkbutton onItemDataBound,然后在onItemCommand上访问它,我已经为你修改了代码,给它一个去吧

    <asp:Repeater ID="Cartridges" runat="server" onitemcommand="Repeater_OnItemCommand" OnItemDataBound="Repeater_OnItemDataBound">
<ItemTemplate>
    <p class="cartprice"><%#String.Format("{0:C}", Eval("Price"))%></p>
    <hr class="hr4" /> 
    <p class="cartqty">QTY <asp:TextBox ID="cartQty" Text="0" runat="server"></asp:TextBox> </p>
    <div class="cartbuy2"><asp:LinkButton ID="buy" runat="server" CommandName="AddtoCart" Text="Buy"></asp:LinkButton></div>

你的onItemdatabound应该是这样的

 protected void Repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {

        //your code...

          LinkButton add = (LinkButton)e.Item.FindControl("buy");
                  add.CommandArgument = cartID.ToString();

    }

然后你可以像这样

访问item命令的文本框
 protected void Repeater_OnItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "AddtoCart")
            {
                LinkButton btnEdit = (LinkButton)e.CommandSource;
                if (btnEdit != null)
                {
                    string editId = btnEdit.CommandArgument;
                    string text = ((TextBox)e.Item.FindControl("cartQty")).Text;
                    //do some stuff with your cartid and quantity
                }
            }
}

您还可以使用编辑/删除命令参数扩展代码,方法是添加更多链接按钮并将它们绑定到正确的命令,然后在项目命令中访问它们 感谢