assign a value from a foreach loop to an asp:button CommandArgument
The code behind file creates a list of employees and the asp.net page loops through list. Now, How do I assign the employeedID to the commandArgument of an asp:button?
<%foreach(var employee in employeesList){%>
<tr>
<td><%=employee开发者_Go百科.firstName%></td>
<td><%=employee.lastName%></td>
/*How to access employee.Id in the commandArgument? */
<td><asp:Button ID="btnDeleteEmployee" runat="server" CommandArgument='' Text="Delete" OnCommand="btnDeleteEmployee_Click" /></td>
</tr>
<%}%>
Based on your comments, here is a nested example:
Markup:
<asp:Repeater runat="server" ID="rptOutter"
onitemdatabound="rptOutter_ItemDataBound" >
<ItemTemplate>
<tr>
<td><%#Eval("firstName") %></td>
<td><%#Eval("lastName") %></td>
<td><asp:Button runat="server" ID="btnDeleteEmployee" CommandArgument='<%#Eval("Id") %>' Text="Delete" OnCommand="btnDeleteEmployee_Click" /></td>
<td>
<asp:Repeater runat="server" ID="rptInner" >
<ItemTemplate>
<table>
<tr>
<td><%#Eval("firstNameInner") %></td>
<td><%#Eval("lastNameInner") %></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
CodeBehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
rptOutter.DataSource = outterDataSource;
rptOutter.DataBind();
}
}
protected void rptOutter_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
RepeaterItem item = e.Item;
if ((item.ItemType == ListItemType.Item) ||
(item.ItemType == ListItemType.AlternatingItem))
{
//get your datasource from parent repeater if needed
//cast to your datasource type
//DataSourceObject ds = (DataSourceObject)item.DataItem;
Repeater r = e.Item.FindControl("rptInner") as Repeater;
if (r != null)
{
r.DataSource = innerDataSource;
r.DataBind();
}
}
}
<asp:Repeater runat="server" ID="rptEmployeeList">
<ItemTemplate>
<tr>
<td><%#Eval("firstName") %></td>
<td><%#Eval("lastName") %></td>
<td><asp:Button runat="server" ID="btnDeleteEmployee" CommandArgument='<%#Eval("Id") %>' Text="Delete" OnCommand="btnDeleteEmployee_Click" /></td>
</tr>
</ItemTemplate>
</asp:Repeater>
and then in the codebehind
if (!Page.IsPostBack)
{
rptEmployeeList.DataSource = employeeList;
rptEmployeeList.DataBind();
}
精彩评论