单击中继器控件内的CheckBox时,我需要在中继器中的一行上做一些服务器端逻辑。
有人知道该怎么做吗?
从我的角度来看,您不能启动项目命令,如果使用CheckBoxes OnClick,则无法获得转发器行。
最佳答案
这是我过去做过类似事情的快速模型。
<asp:Repeater id="repeater1" runat="server" OnItemDataBound="repeater1_OnItemDataBound" >
<ItemTemplate>
<asp:CheckBox ID="chk" runat="server" OnCheckedChanged="Check_Changed" AutoPostBack="true" />
</ItemTemplate>
</asp:Repeater>
代码背后:
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.
}
}
关于c# - 中继器或数据列表中的复选框OnClick/ItemCommand,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3566979/