您可以遍历中继器项目,获取通过的 id 的项目CommandArgument='<%# Bind ("id") %>'
并调用FindControl()
以获取公司名称,这是一个示例:
ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("ID") %>' />
<asp:HiddenField ID="hdCompanyName" runat="server" Value='<%# Eval("CompanyName") %>' />
<asp:Button ID="btnSave" runat="server" OnCommand="Save" CommandArgument='<%# Eval("ID") %>' Text="Save" />
</ItemTemplate>
</asp:Repeater>
后面的代码:
public partial class RepeaterExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var employees = new List<Employee>()
{
new Employee{ Id="1",CompanyName="Company 1"},
new Employee{ Id="2",CompanyName="Company 2"}
};
Repeater1.DataSource = employees;
Repeater1.DataBind();
}
}
protected void Save(object sender, CommandEventArgs e)
{
string id = e.CommandArgument.ToString();
string companyName = string.Empty;
foreach (RepeaterItem item in Repeater1.Items)
{
Label lblId = item.FindControl("lblId") as Label;
if (lblId.Text.Equals(id))
{
companyName = (item.FindControl("hdCompanyName") as HiddenField).Value;
break;
}
}
System.Diagnostics.Debug.WriteLine(companyName);
}
}
public class Employee
{
public string Id { get; set; }
public string CompanyName { get; set; }
}
也许更好的解决方案是将id和公司名称都传递给CommandArgument
this 将避免通过循环通过中继器创建的额外处理:
ASPX:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Eval("ID") %>' />
<asp:HiddenField ID="hdCompanyName" runat="server" Value='<%# Eval("CompanyName") %>' />
<asp:Button ID="btnSave" runat="server" OnCommand="Save" CommandArgument='<%# String.Format("{0},{1}",Eval("ID"),Eval("CompanyName")) %>' Text="Save" />
</ItemTemplate>
</asp:Repeater>
后面的代码:
只需拆分字符串,就有两个参数!
protected void Save(object sender, CommandEventArgs e)
{
string [] arguments = e.CommandArgument.ToString().Split(',');
string id = arguments[0];
string companyName = arguments[1];
}