简体   繁体   English

Repeater或DataList中的复选框OnClick / ItemCommand

[英]Checkbox OnClick/ItemCommand in Repeater or DataList

I need to do some server side logic on a row in my repeater when a CheckBox is clicked inside the repeater control. 当在转发器控件中单击CheckBox时,我需要在转发器中的一行上执行一些服务器端逻辑。

Anyone know how to go about this? 有谁知道如何去做?

The way I see it you cant fire item command and if you use the CheckBoxes OnClick you cant get the repeater row. 我看到它的方式你不能解雇项目命令,如果你使用CheckBoxes OnClick你不能得到转发器行。

Here is a quick mock-up of how I have done similar in the past. 这是我过去做过类似事情的快速模型。

    <asp:Repeater id="repeater1" runat="server" OnItemDataBound="repeater1_OnItemDataBound" >
        <ItemTemplate>
            <asp:CheckBox ID="chk" runat="server" OnCheckedChanged="Check_Changed" AutoPostBack="true" />
        </ItemTemplate>
    </asp:Repeater>

codebehind: 代码隐藏:

    public class Model {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    public partial class Checkboxes : System.Web.UI.Page {
        protected void Page_Load(object sender, EventArgs e) {
            if(!IsPostBack ) {
                repeater1.DataSource = new List<Model> { 
                               new Model { Id = 1, Name = "a" }, 
                               new Model { Id = 2, Name = "b" }, 
                               new Model { Id = 3, Name = "c" } };
                repeater1.DataBind();
            }
        }

        protected void repeater1_OnItemDataBound(Object sender, RepeaterItemEventArgs e) {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) {
                var item = e.Item.DataItem as Model;
                if (item != null) {
                    var chk = e.Item.FindControl("chk") as CheckBox;
                    if (chk != null) {
                        chk.Text = item.Name;
                        chk.InputAttributes.Add("value", item.Id.ToString());
                    }
                }
            }
        }

        protected void Check_Changed(Object sender, EventArgs e) {
            var id = ((CheckBox) sender).InputAttributes["value"];
            //you now have access to the item id and can manipulate at will.
        }
    }

Try this codebehind: 试试这个代码隐藏:

 protected void Checked_Changed(object sender, EventArgs e)
        {
            var item = ((CheckBox)sender).Parent as RepeaterItem;
// now you have the repeater row. You can travers further up the controls if you use Parent.Parent...

        }

You could use the OnClick event to loop through each item in the repeater, and check the value of each checkbox, (IsChecked == true). 您可以使用OnClick事件遍历转发器中的每个项目,并检查每个复选框的值,(IsChecked == true)。

Just make sure that you are not calling a "DataBind()" on the repeater, otherwise that might cause issues. 只需确保您没有在转发器上调用“DataBind()”,否则可能会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM