我正在尝试使用asp:repeater创建按钮
这就是我所拥有的:
<asp:Repeater ID="rptQuery" runat="server">
<ItemTemplate>
<asp:Button runat="server" Text='<%this.GetDataItem().ToString() %>'
OnClick="Unnamed_Click" />
</ItemTemplate>
</asp:Repeater>
我不知道如何更改按钮文本以反映从rptQUery的源(字符串列表)获取的值以及用于引用此特定按钮的onclick事件。
请问任何建议?
答案 0 :(得分:0)
我建议添加一个ItemDataBinding事件并在代码中处理它:
<asp:Repeater ID="rptQuery" runat="server" OnItemDataBound="rptQuery_ItemDataBound">
<ItemTemplate>
<asp:Button id="btnUnnamed" runat="server" OnClick="Unnamed_Click" />
</ItemTemplate>
</asp:Repeater>
然后你的方法看起来像这样。
protected void rptQuery_ItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var data = e.Item.DataItem as string;
var btnUnnamed = e.Item.FindControl("btnUnnamed") as Button;
if (btnUnnamed != null)
{
btnUnnamed.Text = data;
}
}
}
答案 1 :(得分:0)
您可以使用ItemDataBound事件来设置Button控件的绑定和外观。
然后使用Button控件的Command事件来捕获发布的数据。
<asp:Repeater ID="rptQuery" runat="server"
OnItemDataBound="rptQuery_ItemDataBound">
<ItemTemplate>
<asp:Button runat="server" ID="Button1" OnCommand="Button1_Command" />
</ItemTemplate>
</asp:Repeater>
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var customers = new List<Customer>
{
new Customer {Id = 1, Name = "Jon"},
new Customer {Id = 2, Name = "Eric"}
};
rptQuery.DataSource = customers;
rptQuery.DataBind();
}
}
protected void rptQuery_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item ||
e.Item.ItemType == ListItemType.AlternatingItem)
{
var customer = e.Item.DataItem as Customer;
var button = e.Item.FindControl("Button1") as Button;
button.CommandName = customer.Id.ToString();
button.Text = customer.Name;
}
}
protected void Button1_Command(object sender, CommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandName);
// Do something with id
}