Article: ListView in UpdatePanel
Share/Save/Bookmark
Description: This topic will give you the pieces you need to add an ASP.Net ListView control to your page and how to get the values out of the ListView in code behind

Add the update panel and ListView Item to your page.  Notice that the DateKeyNames for the ListView, match the fields I use from the ListItem object that I bind in the Code Behind.

<table>
  <
asp:UpdatePanel ID="upnlModeType" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
     
<!-- Entities -->
     
<asp:ListView ID="lvwEntities" runat="server" DataKeyNames="Text, Value" OnItemDataBound="lvwEntities_ItemDataBound">
       
<LayoutTemplate>
         
<asp:PlaceHolder ID="itemPlaceHolder" runat="server"></asp:PlaceHolder>  
       
</LayoutTemplate>
       
<ItemTemplate>
         
<tr>
           
<td class="TextAlignRight" style="text-align:right">
             
<asp:Label ID="lblEntities" runat="server"></asp:Label>
           
</td><td>
             
<asp:TextBox ID="txtEntities" runat="server"></asp:TextBox>
           
</td>
          
</tr>
       
</ItemTemplate>
      
</asp:ListView>
      
<!-- Entities (end) -->
   
</ContentTemplate>
  </asp:UpdatePanel>
</table>


In the code behind, add code to populate the object (I'm using the ListItem object)
NOTE: I am using LINQ to populate the "entities" collection

List<ListItem> entities = new List<ListItem>();

myObject.ForEach( s=> entities.Add( new ListItem( s.textValue, s.Value) ) );

lvwEntities.DataSource = entities;
lvwEntities.DataBind();


I am using the "Text" value in my ListItem to populate the label in the ListView in the ItemDataBound Event of the control. 
NOTE: you can do this in the ItemCreated Event Handler.  I am doing this on the ItemDataBound because I am changing the values based on the selection of a dropDownList and updating it conditionally.

protected void lvwEntities_ItemDataBound( object sender, ListViewItemEventArgs e )
{
  
if( e.Item.ItemType == ListViewItemType.DataItem )
   {
     
ListViewDataItem currentItem = (ListViewDataItem)e.Item;
     
DataKey currentDataKey = this.lvwEntities.DataKeys[currentItem.DataItemIndex];
    
     
Label lblEntities = (Label)currentItem.FindControl( "lblEntities" );
      lblEntities.Text = (
string)currentDataKey["Text"];
   }
}


The following shows you how to get the values out of the ListView control.  You would do this like on a btnSave event.
List<MyReference> references = new List<MyReference>();

foreach( ListViewDataItem item in lvwEntities.Items )
{
  
if( item.ItemType == ListViewItemType.DataItem )
   {
     
DataKey currentDataKey = this.lvwEntities.DataKeys[item.DataItemIndex];

     
MyReference reference = new MyReference();
 
      reference.REFERENCE_TYPE_ID =
int.Parse( (string)currentDataKey["Value"] );
      reference.REFERENCE_NUMBER = ( (
TextBox)item.FindControl( "txtEntities" ) ).Text;

      references.Add( reference );
   }
}