2015-11-18 16 views
0

蔭訪問列表視圖項目代碼隱藏,我怎麼能訪問值列表視圖形式的代碼背後的按鈕,點擊如何使用列表視圖來顯示錶的內容使用asp.net

ASPX

<LayoutTemplate> 
<table runat="server" id="table1"> 
<tr id="Tr1" runat="server"> 
    <th class="tablehead"id="mname">Movie Name</th> 
    <th class="tablehead">Movie Genre</th> 
    <th class="tablehead">Runtime</th> 

</tr> 
<tr runat="server" id="itemPlaceholder"></tr> 

<ItemTemplate> 
<tr id="Tr2" runat="server" class="tablerw"> 
<td style="background-color:#EEEEEE;width:100px;" class="tablerw"><asp:Label ID="Label5" runat="server" Text='<%#Eval("MovieName") %>' /></td> 
<td style="background-color:#EEEEEE;width:100px;"><asp:Label ID="NameLabel" runat="server" Text='<%#Eval("movieGenre") %>' /></td> 
<td style="background-color:#EEEEEE;width:100px;"><asp:Label ID="Label1" runat="server" Text='<%#Eval("Runtime") %>' /></td> 
<td> 
<asp:Button ID="Button1" runat="server" Text="Approve" OnClick="Button1_Click"></asp:Button>//Here is my button 
</ItemTemplate> 

aspx.cs

protected void Button1_Click(Object sender, 
        System.EventArgs e) 
     { 
     //I want to access value here 
     } 

我想電影名稱,電影類型,運行到後面代碼..任何幫助表示讚賞..

+0

可以複製http://stackoverflow.com/questions/1943032/how-to-access-controls-located-in-the-listview-from-的代碼隱藏 –

+0

儘管FindControl可能(請參閱Kaushik鏈接到的內容),但應該不惜一切代價避免這種情況。由此產生的代碼將容易出錯並難以維護。你不能考慮使用ListVIew的ItemCommand嗎?按鈕可以觸發命令並提供一個Id作爲命令參數。然後在處理程序中從數據庫中獲取數據項。 – Andrei

+0

我同意@Andrei的評論和@Rahul的回答。然而,在您的示例中,您想要將最後一個'​​'更改爲'',以正確關閉您的''標記,並且不會有沒有關閉的'​​'標記。 –

回答

1

正確的方式來處理按鈕控件的Click事件中的數據綁定控件是通過設置CommandArgument & CommandName性質。您可以註冊ListView的一個ItemCommand事件,而不是註冊按鈕的點擊處理程序。這樣,如果點擊了一個按鈕,然後引發此事件,你可以找到正確的數據是這樣的: -

添加CommandName & CommandArgument屬性的按鈕,取出單擊處理: -

<asp:Button ID="Button1" runat="server" Text="Approve" CommandName="GetData" 
      CommandArgument='<%# Eval("MovieId") %>' ></asp:Button> 

下一頁,用你的列表視圖註冊ItemCommand事件: -

<asp:ListView ID="lstMovies" runat="server" OnItemCommand="ListView1_ItemCommand"> 

最後,在後面的代碼,在ListView1_ItemCommand方法檢查,如果事件被引發您的按鈕,並找到所有相應的控制: -

protected void ListView1_ItemCommand(object sender, ListViewCommandEventArgs e) 
{ 
    if (e.CommandName == "GetData") 
    { 
     if (e.CommandSource is Button) 
     { 
      ListViewDataItem item = (e.CommandSource as Button).NamingContainer 
             as ListViewDataItem; 
      Label NameLabel = item.FindControl("NameLabel") as Label; 
      Label Label5 = item.FindControl("Label5") as Label; 
      //and so on.. 
     } 
    } 
} 
相關問題