Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1270
  • Last Modified:

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

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
0
thefridgeVFA
Asked:
thefridgeVFA
  • 2
1 Solution
 
ddayx10Commented:
Here is a seriously super-simplified version of what you are asking(see code).

I'm not sure you need all of this as I think you understand everything except how to get at and bind to the dropdownlist, but just in case I'll post the whole thing.

I've used a really simple dev sql table with 2 columns to bind to. I think it should be self-explanatory. What I think you are most interrested in is the lv_itemdatabound event.

Hope this helps :)
****ASPX PAGE****
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default7.aspx.vb" Inherits="Default7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ListView ID="lv" runat="server" ItemPlaceholderID="iph">
    <LayoutTemplate>
		<div id="iph" runat="server"></div>
    </LayoutTemplate>
		<ItemTemplate>
			<div>
			<asp:Label ID="lblName" runat="server" Text='<%# Eval("Name") %>' />
			<asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" />
			</div>
		</ItemTemplate>
		<EditItemTemplate>
			<asp:dropdownlist ID="ddlNames" runat="server" /><span>test</span>
		</EditItemTemplate>
    </asp:ListView>
    </form>
</body>
</html>


****ASPX.VB CODE BEHIND****
Imports System.Data
Imports System.Data.SqlClient

Partial Class Default7
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then BindListView()
    End Sub


    Protected Sub lv_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles lv.ItemDataBound
        If lv.EditItem IsNot Nothing Then
            Dim di As ListViewDataItem = e.Item
            If di.DisplayIndex = lv.EditIndex Then
                Dim ddl As DropDownList = e.Item.FindControl("ddlNames")
                BindDDL(ddl)
            End If
        End If
    End Sub

    Protected Sub lv_ItemEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewEditEventArgs) Handles lv.ItemEditing
        lv.EditIndex = e.NewEditIndex
        BindListView()
    End Sub

    Private Sub BindListView()
        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DevTest").ConnectionString())
            Using cmd As New SqlCommand("SELECT ItemNumber,Name FROM Items", conn)
                conn.Open()
                lv.DataSource = cmd.ExecuteReader
                lv.DataBind()
                conn.Close() 'unnecessary I know
            End Using
        End Using
    End Sub

    Private Sub BindDDL(ByRef ddl As DropDownList)
        Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DevTest").ConnectionString())
            Using cmd As New SqlCommand("SELECT ItemNumber,Name FROM Items", conn)
                ddl.DataValueField = "ItemNumber"
                ddl.DataTextField = "Name"
                conn.Open()
                ddl.DataSource = cmd.ExecuteReader
                ddl.DataBind()
                conn.Close() 'unnecessary I know
            End Using
        End Using
    End Sub


End Class

Open in new window

0
 
ddayx10Commented:
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

0
 
thefridgeVFAAuthor 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.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now