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

C# Label 控件綁定文本無法響應點擊獲取索引:需改用 ListView/Repeater

     編輯:程式設計綜合問答

題主將多行數據拼接字符串賦給單個 `Label.Text`,再想在 `Label.Click` 中知道用戶點擊了第幾行 — **Label 不具備行級點擊感知能力**,渲染出來只是一塊純文本。

正確控件選擇

場景推薦控件核心屬性/事件
WebForms 列表`Repeater` / `ListView` / `GridView``ItemCommand` / `RowCommand` + `CommandArgument` 綁定索引/ID
WinForms 列表`ListView` (Details) / `DataGridView``ItemActivate` / `CellClick` + `Tag` / `Rows[e.RowIndex].Cells["Id"].Value`
WPF 列表`ListView` / `DataGrid` / `ItemsControl``MouseDoubleClick` + `SelectedItem` (MVVM 綁定命令)

WebForms Repeater 示例

<asp:Repeater ID="rptData" runat="server" OnItemCommand="rptData_ItemCommand">
    <ItemTemplate>
        <a href="#" class="item-link" 
           <%# "onclick=\"return doClick(" + Container.ItemIndex + ");\"" %>>
            <%# Eval("G_Title") %>
        </a><br />
    </ItemTemplate>
</asp:Repeater>

protected void rptData_ItemCommand(object source, RepeaterCommandEventArgs e) {
    int index = e.Item.ItemIndex; // 獲取行索引
    string title = (e.Item.FindControl("lblTitle") as Label).Text;
    // 業務邏輯
}

結論:**不要嘗試用 Label 承載列表交互**,選對控件事半功倍。

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