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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.
}
}
Method 2
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...
}
Method 3
You could use the OnClick event to loop through each item in the repeater, and check the value of each checkbox, (IsChecked == true).
Just make sure that you are not calling a “DataBind()” on the repeater, otherwise that might cause issues.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0