We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x

Want databound (via code behind window) asp:DropDownList in EditItemTemplate and InsertItemTemplate of asp:ListView

thefridgeVFA
thefridgeVFA asked
on
Medium Priority
1,361 Views
Last Modified: 2012-06-27
I am working on a web site in VS2008 targeting Framework 3.5. I have an asp:ListView which is databound via LINQ and it works great.  In all of my prior ListView controls, I used an asp:TextBox control in the EditItemTemplate and InsertItemTemplate.  Now I want to limit the user's input via a databound asp:DropDownList, but I cannot get it to work. How is it done?

I prefer to do everything possible in the code behind window.

The database has two simple tables;  Tables and DataContextThe are two records in tblStreet and one record in tblAddress;  Design view of Default.aspxHere is what startup looks like;  Debug startup
Here is the ASP.Net code;

<%@ Page Language="VB" Debug="true" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<asp:Content ID="ContentPlaceholder1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ListView ID="ListView1" runat="server" InsertItemPosition="LastItem"
            onitemcanceling="ListView1_ItemCanceling"
            onitemediting="ListView1_ItemEditing"
            onitemupdating="ListView1_ItemUpdating"
            onitemdeleting="ListView1_ItemDeleting"
            oniteminserting="ListView1_ItemInserting">
        <LayoutTemplate>
            <table id="Table1" runat="server" >
                <tr id="Tr1" runat="server">
                    <td id="Td1" runat="server">
                        <table ID="itemPlaceholderContainer" runat="server" border="0" style="">
                            <tr id="Tr2" runat="server" style="">
                                <th id="Th1" runat="server"></th>
                                <th id="Th2" runat="server">ID</th>
                                <th id="Th3" runat="server" align="left">Number</th>
                                <th id="Th4" runat="server" align="left">Street</th>
                            </tr>
                            <tr ID="itemPlaceholder" runat="server">
                            </tr>
                        </table>
                    </td>
                </tr>
                <tr id="Tr3" runat="server">
                    <td id="Td2" runat="server" style="">
                    </td>
                </tr>
                <tr id="Tr4" runat="server">
                    <td id="Td3" runat="server" style="">
                        <asp:DataPager ID="DataPager1" runat="server">
                            <Fields>
                                <asp:NextPreviousPagerField ButtonType="Link" ShowFirstPageButton="True"
                                    ShowPreviousPageButton="True" ShowNextPageButton="False" ShowLastPageButton="False" />
                                <asp:NumericPagerField />
                                <asp:NextPreviousPagerField ButtonType="link" ShowFirstPageButton="False"
                                    ShowPreviousPageButton="False" ShowNextPageButton="True" ShowLastPageButton="True" />
                            </Fields>
                        </asp:DataPager>
                    </td>
                </tr>
            </table>
        </LayoutTemplate>
        <ItemTemplate>
            <tr class="item" style="">
                <td>
                    <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
                    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                </td>
                <td>
                    <asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>' />
                </td>
                <td>
                    <asp:Label ID="lblStreet" runat="server" Text='<%# Eval("Street") %>' />
                </td>
            </tr>
        </ItemTemplate>
        <AlternatingItemTemplate>
            <tr class="alternatingItem" style="">
                <td>
                    <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" />
                    <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
                </td>
                <td>
                    <asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:Label ID="lblNumber" runat="server" Text='<%# Eval("Number") %>' />
                </td>
                <td>
                    <asp:Label ID="lblStreet" runat="server" Text='<%# Eval("Street") %>' />
                </td>
            </tr>
        </AlternatingItemTemplate>
        <EditItemTemplate>
            <tr style="">
                <td>
                    <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
                    <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
                </td>
                <td>
                    <asp:Label ID="lblID" runat="server" Text='<%# Eval("ID") %>' />
                </td>
                <td>
                    <asp:TextBox ID="lblNumber" runat="server" Text='<%# Eval("Number") %>' />
                </td>
                <td>
                    Street:<asp:dropdownlist ID="ddlStreetEdit" runat="server" AutoPostBack="true">

                    </asp:dropdownlist>
                </td>
            </tr>
        </EditItemTemplate>
        <InsertItemTemplate>
            <tr style="">
                <td>
                    <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Insert" />
                    <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Clear" />
                </td>
                <td>
                    &nbsp
                </td>
                <td>
                    Number:<asp:TextBox ID="txtNumberInsert" runat="server" />
                </td>
                <td>
                    Street:<asp:dropdownlist ID="ddlStreetInsert" runat="server" AutoPostBack="true">

                    </asp:dropdownlist>
                </td>
            </tr>
        </InsertItemTemplate>
    </asp:ListView>    
</asp:Content>



Here is the code behind window;

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            'bind data to ListView1
            BindListView1()
        End If
    End Sub

    Protected Sub BindListView1()
        Dim db As New MyDatabaseDataContext()
        'get all records from tblAddress
        Dim qA As IEnumerable(Of tblAddress) = db.tblAddresses
        'bind to ListView1
        Me.ListView1.DataSource = qA.ToArray() 'requires ICollection
        Me.ListView1.DataBind()
    End Sub

    Protected Sub Bind_ddlStreetEdit()
        Dim db As New MyDatabaseDataContext()
        'get all rows from column "Name" from tblStreet for ddlStreetFilter, sorted alphabetically
        Dim Names = db.tblStreets.OrderBy(Function(o) o.Street).Select(Function(n) n.Street).ToList
        ''first attempt had error; 'ddlStreetEdit' is not a member of '_Default'.
        'Me.ddlStreetEdit.DataSource = Names 'requires ICollection
        'Me.ddlStreetEdit.DataBind()
        'Me.ddlStreetInsert.DataSource = Names 'requires ICollection
        'Me.ddlStreetInsert.DataBind()

        'second attempt would build but threw runtime error; Object reference not set to an instance of an object.
        Dim ddlTemp As DropDownList = Me.FindControl("ddlStreetEdit")
        ddlTemp.DataSource = Names 'requires ICollection
        ddlTemp.DataBind()
    End Sub

    Protected Sub ListView1_PagePropertiesChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles ListView1.PagePropertiesChanging
        Dim pager As DataPager = DirectCast(DirectCast(sender, ListView).FindControl("DataPager1"), DataPager)
        pager.SetPageProperties(e.StartRowIndex, e.MaximumRows, False)

        BindListView1()

        'bind data to ddlStreetEdit

    End Sub


    Protected Sub ListView1_ItemEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewEditEventArgs) Handles ListView1.ItemEditing
        ListView1.EditIndex = e.NewEditIndex
        BindListView1()
        Dim db As New MyDatabaseDataContext()
        'get all rows from column "Street" from tblStreet for ddlStreetEdit, sorted alphabetically
        Dim Names = db.tblStreets.OrderBy(Function(o) o.Street).Select(Function(n) n.Street).ToList

        'TODO: runtime error; Object reference not set to an instance of an object.
        Dim ddlTemp As DropDownList = Me.FindControl("ddlStreetEdit")
        ddlTemp.DataSource = Names 'requires ICollection
        ddlTemp.DataBind()

        'find control with ID for record about to be edited
        Dim lblTemp As Label = TryCast(ListView1.EditItem.FindControl("lblID"), Label)
        If lblTemp IsNot Nothing Then
            Dim aID As String = lblTemp.Text
            Dim a As tblAddress = db.tblAddresses.Where(Function(r) r.ID = CLng(aID)).First 'gets record about to be edited
        End If
    End Sub

    Protected Sub ListView1_ItemCanceling(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCancelEventArgs) Handles ListView1.ItemCanceling
        ListView1.EditIndex = -1
        BindListView1()
    End Sub

    Protected Sub ListView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles ListView1.ItemUpdating
        'save row being edited
        Dim lblTemp As Label = TryCast(ListView1.Items(e.ItemIndex).FindControl("lblID"), Label)
        Dim db As New MyDatabaseDataContext()
        If lblTemp IsNot Nothing Then
            Dim aID As String = lblTemp.Text
            Dim addr As tblAddress = db.tblAddresses.Where(Function(r) r.ID = CLng(aID)).First 'gets record in DB being edited
            Dim ddlTemp As DropDownList = TryCast(ListView1.Items(e.ItemIndex).FindControl("ddlStreetEdit"), DropDownList)
            If ddlTemp IsNot Nothing Then
                addr.Street = ddlTemp.Text
                db.SubmitChanges()
                ListView1.EditIndex = -1
                BindListView1()
            End If
        End If
    End Sub

    Protected Sub ListView1_ItemDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewDeleteEventArgs) Handles ListView1.ItemDeleting
        Dim lblTemp As Label = TryCast(ListView1.Items(e.ItemIndex).FindControl("lblID"), Label)
        Dim db As New MyDatabaseDataContext()
        If lblTemp IsNot Nothing Then
            Dim aID As String = lblTemp.Text
            Dim addr As tblAddress = db.tblAddresses.Where(Function(r) r.ID = CLng(aID)).First 'gets record being deleted
            db.tblAddresses.DeleteOnSubmit(addr)
            db.SubmitChanges()
            'refresh page (to see updated table)
            Response.Redirect(Request.Url.ToString)
        End If
    End Sub

    Protected Sub ListView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewInsertEventArgs) Handles ListView1.ItemInserting
        Dim txtNumber As TextBox = TryCast(e.Item.FindControl("txtNumberInsert"), TextBox)
        Dim ddlStreet As DropDownList = TryCast(e.Item.FindControl("ddlStreetInsert"), DropDownList)
        'LINQ - instantiate new object with properties from UI controls
        Dim db As New MyDatabaseDataContext()
        Dim newAddress As New tblAddress With { _
            .Number = txtNumber.Text, _
            .Street = ddlStreet.Text}
        db.tblAddresses.InsertOnSubmit(newAddress)
        db.SubmitChanges()
        'refresh page (to see updated status)
        Response.Redirect(Request.Url.ToString)
    End Sub

End Class
Comment
Watch Question

Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Commented:
If you wanted to go without the "assurancy" checking and with more streamlined look you might do this:
Protected Sub lv_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lv.ItemDataBound
    If DirectCast(e.Item, ListViewDataItem).DisplayIndex = lv.EditIndex Then
        Dim ddl As DropDownList = e.Item.FindControl("ddlNames")
        BindDDL(ddl)
    End If
End Sub

Open in new window

Author

Commented:
Thanks!. I'm still having trouble with editing and inserting. I'll post another question later today if I don't figure it out.
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.