I have a list of items that are retrieved and can have varying amounts. Because of this, I have a Repeater to create a dynamic amount of rows to display each item in. I need a button in each row that can change some of the properties of the item in the list for that specific row. I'm only able to create the same button for each row in the aspx file which means I have no way to determine which row to change because all of the buttons are the same. See below:
<asp:Repeater runat="server" ID="repeater">
<ItemTemplate>
<li class="list-group-item"><%# Container.DataItem %>
<asp:Button ID="btn" runat="server" />
</li>
</ItemTemplate>
</asp:Repeater>
The list items are displayed with a loop, so i've removed the button from the aspx page and instead tried to create buttons in this loop but they are not displaying.
for (int i = 0; i < listItems.Length; i++)
{
openList.Add("ID: " + item[i]);
repeater.DataSource = openList;
Button btn = new Button();
btn.ID = i.ToString();
repeater.Controls.Add(btn);
repeater.DataBind();
}
Don't worry. The buttons are not the same. The framework will ensure that they are unique. And if you want to know which button was clicked, you can send a CommandArgument
to the OnCommand
method.
<asp:Repeater runat="server" ID="repeater">
<ItemTemplate>
<li class="list-group-item"><%# Container.ItemIndex %>
<asp:Button ID="btn" runat="server" CommandArgument='<%# Container.ItemIndex %>' OnCommand="btn_Command" />
</li>
</ItemTemplate>
</asp:Repeater>
Code behind
protected void btn_Command(object sender, CommandEventArgs e)
{
//if you need to access the button itself
Button btn = sender as Button;
//get the correct index from the commandargument
Label1.Text = e.CommandArgument.ToString();
}