简体   繁体   中英

How to access Listview items to codebehind using asp.net

Iam using a listview to display table contents,How can i access a values form listview to code behind in button click

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
      }

I want to get Movie Name,Movie Genre,Runtime to code behind.. Any help is appreciated..

Proper way to deal with button control click event in data bound controls is by setting a CommandArgument & CommandName properties. Instead of registering a click handler of button you can register a ItemCommand event of ListView. This way whenever a button is clicked then this event is raised and you can find the data correctly like this:-

Add CommandName & CommandArgument properties to your button and remove the click handler:-

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

Next, register the ItemCommand event with your listview:-

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

Finally in the code behind, in ListView1_ItemCommand method check if event is raised by your button and find all the respective controls:-

 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..
         }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM