Click here to Skip to main content
15,903,033 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to use drop down list in my code (Asp.net). I want to make first value as hard coded ("Select City" in my case) while remaining values will come from database. How i can do that. Mean first values will be hard coded, while remaining will be dynamic .

What I have tried:

<asp:DropDownList ID="ddlGender" runat="server" Width="200px">
<asp:ListItem Text="Select City" >
Posted
Updated 19-Mar-17 8:01am

1 solution

try like this

var itemsFromDb = getData();
for (int i = 0; i < itemsFromDb.Length; i++)
    ddlGender.Items.Add(itemsFromDb[i]);
 
Share this answer
 
Comments
Hassaan_Malik 19-Mar-17 14:05pm    
Then where would be my hard coded value , like "Select Country" because in you solution my whole values will come from database. isn't it??
Karthik_Mahalingam 19-Mar-17 14:09pm    
yes, along with "Select country", all the values from db also will be appended to the list.

mark up be like
<asp:DropDownList ID="ddlGender" runat="server" Width="200px">
<asp:ListItem Text="Select City" >
Hassaan_Malik 19-Mar-17 14:10pm    
Really extremely sorry. I am beginner to asp.net. Can you provide with sample code, if you have. I will be highly thankful to you?Because i am not getting the point.
Karthik_Mahalingam 19-Mar-17 14:15pm    
     protected void Page_Load(object sender, EventArgs e)
            {
                if (!Page.IsPostBack) { 
                var itemsFromDb = getGenderData();
                ddlGender.Items.Add("Select Gender");
                for (int i = 0; i < itemsFromDb.Length; i++)
                    ddlGender.Items.Add(itemsFromDb[i]);}
         

            }

            public string[] getGenderData()
            {
                return new string[] { "Male", "Female", "Transgender" };
            }


 <asp:DropDownList ID="ddlGender" runat="server" Width="200px">             
        </asp:DropDownList>
Hassaan_Malik 19-Mar-17 14:18pm    
Thanks a lot. Its really helpful. Thanks for your cooperation.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900