Kanchan Sharma Kanchan Sharma - 5 months ago 17
C# Question

how to add options in <select> tag at page load dynamically using c#?

I am populating cascaded elements from database using jquery ajax. There is just one problem I am unable add the default "select program" option at top to my first element dynamically. C# code is doing nothing but i used jquery prepend method to do so and it adds the value but it does not show up when the page loads instead of that the first value that it gets from database is displayed first. This is my code to retrieve data from database and I am Calling it at page load

public void GetPrograms()
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
SqlCommand cmd = new SqlCommand("spGetPrograms", con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adp.Fill(ds, "Programs");
program.DataSource = ds;
program.DataValueField = "ProgID";
program.DataTextField = "ProgName";

these are screen shots of page

page loaded without select program option displayed

select option is there but is not selected by default

this is jquery code

$("#program").prepend(new Option("Select Program", "0"));

Please help
thank you


You can do this at server-side itself

program.Items.Insert(0, "Select Program");

Update As OP wants to do it from Client side:

<select id="program">
      <option>Option 1</option>
      <option>Option 2</option>
      <option>Option 3</option>



  $("select#program").prepend("<option value='0'>Select</option>");

fiddle - https://jsfiddle.net/wj00esyz/