German Wear Discount Shop - Click Here Write for Dotnet-friends and earn for your each submission [Dot]Net-Friends
Skip Navigation Links
Home
Latest
Fast Code
Articles
Tutorials
Online Resources
Forums
Login   | Hi, Guest


Add a new Item to a DropDownList which was filled through a database

Written by omerkamal on Jul 03, 2007
How to add a new Item to a DropDownList which was created and populated usings its DataSource property?

Explanation:

We are going to explain it through a small example. Here we are creating a "DropDownList" which will be filled with years data. 

The simple DropDownList look like this:

<asp:DropDownList ID="DropDownListYear" runat="server">asp:DropDownList>

Now, we want to add a reqiuerd Field Validator. So User have to select any field from years. Here is the Reqiuerd Filed validator code.

:RequiredFieldValidator ID="RequiredFieldValidator3" Display="Dynamic" runat="server" InitialValue="[Year]" ControlToValidate="DropDownListYear" rrorMessage="Select Year">*asp:RequiredFieldValidator>

After that we have fixed the sketch of our DropDownlist. We are going Populate the DropDownList with its Data. Following is the code behind: 

   protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            int currYear = DateTime.Now.Year - 10;

            int[] years = new int[91];

            for (int i = currYear; i > currYear - 91; i--)

            {

                years[currYear - i] = i;

            }

 

            DropDownListYear.DataSource = years;

            DropDownListYear.DataBind();

 

            ListItem listitm = new ListItem("[Year]");

            listitm.Selected = true; //make it DropDownList default item

            DropDownListYear.Items.Insert(0, listitm);

 

   }

}

 

Visitors/Readers Comments
(for questions please use The Forum)



vasanthi
hi,

instead of using that,

we can use this,

DropDownListYear.Items.Insert(0,"Listlitemvalue")


20/05/2008 02:41:58 UTC




Add your Comments

Name:  
Message:
Note: For faster response please use Forums >> for your questions instead of the comments area! (Admin)