在 DataList 模板中使用 Eval("UserId") 綁定數據後,如何在按鈕點擊事件中獲取對應行的綁定值?核心思路:通過 NamingContainer 定位行,再 FindControl 取控件值。
<asp:DataList ID="DataList1" runat="server" OnItemCommand="DataList1_ItemCommand">
<ItemTemplate>
<tr id="producttitle">
<asp:Label ID="Label1" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "vcproduct_title") %>' />
</tr>
<asp:Button ID="btnAdd" runat="server" CommandName="Add"
Text="添加" CommandArgument='<%# Eval("ProductID") %>' />
</ItemTemplate>
</asp:DataList>
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e) {
if (e.CommandName == "Add") {
// 方法 1:直接獲取 CommandArgument(推薦用於主鍵 ID)
string productId = e.CommandArgument.ToString();
// 方法 2:通過 FindControl 獲取模板中其他控件值
DataListItem item = e.Item; // 當前行
Label lblTitle = (Label)item.FindControl("Label1");
if (lblTitle != null) {
string title = lblTitle.Text; // 獲取 vcproduct_title 值
}
}
}
protected void Add_Click(object sender, EventArgs e) {
Button btn = sender as Button;
if (btn != null) {
DataListItem item = btn.NamingContainer as DataListItem; // 關鍵:獲取所在行容器
if (item != null) {
Label lbl = item.FindControl("Label1") as Label;
string title = lbl.Text.ToString(); // 獲取 Eval 綁定的值
}
}
}
Control,標識數據綁定容器(DataListItem/GridViewRow/RepeaterItem)。e.Item 和 e.CommandArgument,比按鈕 Click 更規範。建議:優先用 CommandArgument 傳主鍵,複雜字段用 FindControl,代碼更清晰高效。