Wednesday, 17 October 2012

How to create data bound DropDownList

Get the selected value from dropdown list:
wsLabel.Text = wsDropDownList.SelectedValue.ToString();

Dynamically add Item to the drop down list:

Method 1:
Either you sort the DropDownList after the items have been added, using a custom method (seehttp://www.codeproject.com/KB/webforms/Sort__a_dropdown_box.aspx for an example).
Or you could add the items to a generic List first, then sort that list and after that add the sorted list to the DropDownList using the AddRange method. 
using System.Collections.Generics;
...
List<ListItem> items = new List<ListItem>();

items.Add(new ListItem("Item 2", "Value 2"));

items.Add(new ListItem("Item 1", "Value 1"));

items.Add(new ListItem("Item 3", "Value 3"));

items.Sort(delegate(ListItem item1, ListItem item2) { return item1.Text.CompareTo(item2.Text); });

dropdown.Items.AddRange(items.ToArray());

Method 2:
try this : adding items to DDL in one shot.
private void Page_Load(object sender, System.EventArgs e)
        {
            if(!IsPostBack)
            {
                SqlConnection myConn = new SqlConnection(
                    "Server=localhost;Database=Pubs;Integrated Security=SSPI");
                SqlCommand myCmd = new SqlCommand(
                    "SELECT au_id, au_lname FROM Authors", myConn);
                myConn.Open();
                SqlDataReader myReader = myCmd.ExecuteReader();

                //Set up the data binding.
                AuthorList.DataSource = myReader;
                AuthorList.DataTextField = "au_lname";
                AuthorList.DataValueField = "au_id";
                AuthorList.DataBind();

                //Close the connection.
                myConn.Close();
                myReader.Close();

                //Add the item at the first position.
                AuthorList.Items.Insert(0, "<-- Select -->");

            }

        }
Clear all the item from Drop Down List:
DropDownListBox1.Items.Clear(); 

No comments:

Post a Comment