Hello,
I'm trying to fill a dropdownlist with values in groups. Here's the code working in a single page. If I try the same code in master/content pages I can't get data in groups.
Database: Northwind
- <asp:DropDownList ID="ddlNames" runat="server">
- </asp:DropDownList>
- <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
- <script type="text/javascript">
- $(function () {
- GroupDropdownlist('ddlNames')
- });
- function GroupDropdownlist(id) {
- var selectControl = $('#' + id);
- var groups = [];
- $(selectControl).find('option').each(function () {
- groups.push($(this).attr('data-group'));
- });
- var uniqueGroup = groups.filter(function (itm, i, a) {
- return i == a.indexOf(itm);
- });
- $(uniqueGroup).each(function () {
- var Group = jQuery('<optgroup/>', { label: $(this)[0] }).appendTo(selectControl);
- var grpItems = $(selectControl).find('option[data-group="' + $(this)[0] + '"]');
- $(grpItems).each(function () {
- var item = $(this);
- item.appendTo(Group);
- });
- });
- }
- </script>
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!this.IsPostBack)
- {
- string str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
- SqlConnection conn = new SqlConnection(str);
- conn.Open();
- SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName,TitleOfCourtesy FROM Employees", conn);
- SqlDataAdapter da = new SqlDataAdapter(cmd);
- DataTable dt = new DataTable();
- da.Fill(dt);
- foreach (DataRow row in dt.Rows)
- {
- ListItem item = new ListItem();
- item.Text = row["FirstName"].ToString();
- item.Value = row["EmployeeID"].ToString();
- item.Attributes["data-group"] = row["TitleOfCourtesy"].ToString();
- ddlNames.Items.Add(item);
- }
- conn.Close();
- }
- }
I already tried the following:
1. Had the js code imported to master page as seperate .js file.
2 Changed GroupDropdownlist('ddlNames') to GroupDropdownlist('<%=ddlNames.ClientID %>')
Any kind of help would be appreciated.
Thank you in advance.