Skip to content

Dynamically adding and binding items to asp:DropDownList

August 7, 2011

I had recently discovered an alternative way to populate a dynamically drop down list for controls when trying to find a way to get round a problem which only worked on old controls, only to later to find out that this wasn’t the cause of the problem, it was something else.

Anyway, I used a script to dynamically populate an drop down list, by adding some color items to an ArrayList in, and binding the ArrayList to the dropdown list in script, which I didn’t know was possible. It also includes code on how to dynamically bind different font items to a drop down list aswell. Here is the code.

<%@ Page Language=“VB” %>
<script runat=“server”>
    Dim ColorList(6as String
    Dim FontList as new ArrayList()
    Sub Page_Load
      FontList.Add(“Times New Roman”)
      FontList.Add(“Comic Sans MS”)
      If Not Page.IsPostback
        Dim ColorName as String
        For Each ColorName in ColorList
        ddlFontList.DataSource = FontList
      End If
    End Sub
    Sub btnSelectColor_Click(sender As Object, e As EventArgs)
      lblOutputMessage.Text = “You selected ” & _
        ddlColorList.SelectedItem.Value & ” text written in ” & _
      lblOutputMessage.ForeColor = _
      lblOutputMessage.Font.Name = _
    End Sub
    Sub btnAddFont_Click(sender As Object, e As EventArgs)
      ddlFontList.DataSource = FontList
    End Sub

    <form runat=“server”>
            Select a color from the list:<asp:DropDownList id=“ddlColorList” runat=“server”></asp:DropDownList>
            Then select a font sytle from the list: 
            <asp:DropDownList id=“ddlFontList” runat=“server”></asp:DropDownList>
            &nbsp;<asp:Button id=“btnSelectColor” onclick=“btnSelectColor_Click” runat=“server” Text=“Click here!”></asp:Button>
            <asp:Label id=“lblOutputMessage” runat=“server”></asp:Label>
            Enter a new font for the list:<asp:TextBox id=“txtAddFont” runat=“server”></asp:TextBox>
            <asp:Button id=“btnAddFont” onclick=“btnAddFont_Click” runat=“server” Text=“Add New Font”></asp:Button>


From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: