Add default value to dropdown

I have a dropdown list that takes it's values from a database. But what I would like to be able to do is to set the first item in the dropdown list manully.

This is how you you will do it. run sample code

<%@ Page Language="C#" %>
<%@ import namespace="System.Collections" %>
<script runat="server">

    void Page_Load(object sender, EventArgs e) {
        mydropdown.DataSource = getdata();
        mydropdown.DataBind();
        mydropdown.Items.Insert(0,new ListItem("N/A","N/A"));
    }

    ArrayList getdata(){
        ArrayList result = new ArrayList();
        result.Add(new data("One","1"));
        result.Add(new data("Two","2"));
        result.Add(new data("Three","3"));
        result.Add(new data("Four","4"));
        return result;
    }

    public class data{
        public string _Name;
        public string _Value;
        public data(string name,string val){
            _Name = name;
            _Value = val;
        }
        public string Name {get {return _Name;}}
        public string Value {get {return _Value;}}
    }
</script>
<html>
<head>
</head>
<body>
    <form runat="server">
        <p>First Item "N/A" was added after databinding.
         using DropDownList.Items.Insert method</p>
     <p>mydropdown.Items.Insert(0,new ListItem("N/A","N/A"));</p>
  <asp:DropDownList runat="server" id="mydropdown"
            datatextfield="Name" datavaluefield="Value" />
    </form>
</body>
</html>

UPDATES:

2.0 has easy way to do same just set attribute AppendDataBoundItems="true" and it won't remove default item from ListItem collection.

 
<asp:dropdownlist id=mydropdown runat="server" 
      datavaluefield="Value" datatextfield="Name" 
      appenddatabounditems="true">
      <asp:listitem value="NA">NA</asp:listitem>
</asp:dropdownlist>
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories