I am trying to create buttons using asp:repeater
This is what I have:
<asp:Repeater ID="rptQuery" runat="server">
<ItemTemplate>
<asp:Button runat="server" Text='<%this.GetDataItem().ToString() %>'
OnClick="Unnamed_Click" />
</ItemTemplate>
</asp:Repeater>
I have no idea how to change the button text to reflect the value obtained from rptQUery's source ( a list of strings) and the onclick event to refer to this particular button.
Any advice please?
You can use ItemDataBound event to maniupluate the binding and appearance of Button control.
Then use Command event of the Button control to capture the posted data.
<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
}