Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll
<Asp.net blog>
<personal site>
[prev. Lesson]  UCs: Header and Footer Example
     [next Lesson]  UCs: Loading Programatically Amazon Books

User Control: Simplifies Database Lists by Charles Carroll

This page demonstrates how to use a User Control to re-use some code that populates a data list. The page:

   filename=\experiments\usercontrols\dblistv2.aspx

<Test Script Below>


<%@ Page Language="VB" explicit="false"%>
<%@ Register TagPrefix="dblist" tagname="mylist" src="dblistv2.ascx"%>
<script language="Vb" runat="server">
Sub Page_Load(Src As Object, E As EventArgs) 
    dim conn as string = "PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=" & server.mappath("/experiments/data/biblio.mdb") & ";"
    
    cy.connection=conn
    cy.SQL="select distinct city from Publishers"
    cy.textfield="city"
    cy.valuefield="city"

    
    st.connection=conn
    st.SQL="select distinct state from Publishers"
    st.textfield="state"
    st.valuefield="state"

    
    zp.connection=conn
    zp.SQL="select distinct zip from Publishers"
    zp.textfield="zip"
    zp.valuefield="zip"

End Sub
</script>
<html><head>
<title>Listboxes from Database</title>
</head>
<body bgcolor="#FFFFFF">
<h3>City, State, Zip Lists</font></h3>
<form runat="server">
<asp:Table runat="server" GridLines="both" BorderWidth="1px">
<asp:TableRow>
<asp:TableCell>City</asp:TableCell>
<asp:TableCell><dblist:mylist id="cy" runat="server"/></asp:TableCell>
</asp:TableRow>

<asp:TableRow>
<asp:TableCell>State</asp:TableCell>
<asp:TableCell><dblist:mylist id="st" runat="server"/></asp:TableCell>
</asp:TableRow>

<asp:TableRow>
<asp:TableCell>Zip</asp:TableCell>
<asp:TableCell><dblist:mylist id="zp" runat="server"/></asp:TableCell>
</asp:TableRow>
</asp:Table>
</form>
</body></html>




The User Control:

filename=\experiments\usercontrols\dblistv2.ascx


<%@ Import Namespace="System.Data.oledb" %>
<script language="vb" runat="server">
Public connection AS string
Public SQL AS string
Public tablename as string
public valuefield as string 
public textfield as string
Sub Page_Load(Src As Object, E As EventArgs) 
    Dim Conn as New OLEDBConnection(Connection) 
    Dim Cmd as New OLEDBCommand(SQL,Conn) 
    Conn.Open() 
    thelist.DataSource = Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection) 
    thelist.datatextfield=textfield
    thelist.datavaluefield=valuefield
    thelist.DataBind() 
End Sub
</script>
<ASP:DropDownList id="thelist" runat="server"/>
There are many worthy charities!!. But perhaps help starving children in Africa or South America AND help Charles too. a $5 tip buys him lunch at McDonalds, a $20 tip buys his kid Hitoshi a new computer game, a $39 tip buys his daughter Michiko a few nice outfits. See our donor list.