Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
622 views
in Technique[技术] by (71.8m points)

c# - 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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.
        }
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...