Kanchan Sharma Kanchan Sharma - 3 months ago 8
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");
con.Open();
program.DataSource = ds;
program.DataValueField = "ProgID";
program.DataTextField = "ProgName";
program.DataBind();
con.Close();
}
}


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

Answer

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>

jQuery:

$(document).ready(function(){

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

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