首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

ASP.NET DataList 中獲取 Eval 綁定值的完整方案

     編輯:程式設計綜合問答

在 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 綁定的值
        }
    }
}

關鍵點總結

  • NamingContainer:繼承自 Control,標識數據綁定容器(DataListItem/GridViewRow/RepeaterItem)。
  • FindControl:在容器內遞歸查找控件 ID,避免全頁面同名衝突。
  • CommandArgument:傳遞主鍵 ID 最簡潔,無需 FindControl。
  • ItemCommand 事件:DataList 專用事件,直接提供 e.Item 和 e.CommandArgument,比按鈕 Click 更規範。

建議:優先用 CommandArgument 傳主鍵,複雜字段用 FindControl,代碼更清晰高效。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved