The ASP.NET 3.5 listview control is a great tool in the arsenal of a web developer! Coming from classic ASP, I thought the gridview was the best thing since sliced bread, but it has been well trumped by the listview. A really cool thing about the listview is the ability to insert a new item, straight out-of-the-box.

This feature is great until you want to put a drop-down box in the InsertItem template. I was hit by an error and I figure it is a result of there being no data for the drop-down to set as it's selected value when it loads. So, what do we do to fix this? Well here is my solution:

ASPX ListView Code

In the ListView control, navigate to your InsertItemTemplate tag. Place a drop-down list control in the column (<td>) where you want. Below I am using an Entity Data Source (Provided by the ADO.NET Entity Framework), but you could bind it any data source you want or add values in your code behind.

   1: <InsertItemTemplate>
   2:     <tr style="background-color: #05A705;">
   3:         <td>
   4:             <asp:DropDownList ID="ddlExample" runat="server" DataSourceID="EntityDataSource" DataTextField="DataName"
   5:                 DataValueField="DataID" AppendDataBoundItems="true">
   6:                 <asp:ListItem Selected="True" Text="Select a Value" Value="" />
   7:             </asp:DropDownList>
   8:         </td>
   9:     </tr>
  10: </InsertItemTemplate>

 

 

Notice how I don't have a "SelectedItem" tag in the Drop-down list control. Putting this in will cause all sorts of issues and you'll probably get an error that looks similar to this:

System.InvalidOperationException: Databinding methods such as Eval(), XPath(), and Bind() can only be used in the context of a databound control

On Item Inserting

Because the above drop-down list isn't bound to the ListView, we need to handle the inserting ourselves. The code below shows how to modify the ListView property with a value we want, namely the selected item in the drop-down list. In the code I have to find the drop-down list in the InsertItem Template.

   1: Private Sub lvExample_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles lvExample.ItemInserting
   2:     e.Values("ExampleID") = DirectCast( _
   3:                 lvExample.InsertItem.FindControl("ddlExample"), DropDownList).SelectedValue
   4: End Sub

The above code can be used to add any values to items in your ListView.