Chriz L

Chriz L

  • NA
  • 220
  • 51.1k

Fill dropdownlist with value in groups (Master/content page)

Jun 5 2018 2:38 AM
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 
  1. <asp:DropDownList ID="ddlNames" runat="server">    
  2. </asp:DropDownList>    
  3. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>    
  4. <script type="text/javascript">    
  5. $(function () {    
  6.     GroupDropdownlist('ddlNames')    
  7. });    
  8. function GroupDropdownlist(id) {    
  9.     var selectControl = $('#' + id);    
  10.     var groups = [];    
  11.     $(selectControl).find('option').each(function () {    
  12.         groups.push($(this).attr('data-group'));    
  13.     });    
  14.     var uniqueGroup = groups.filter(function (itm, i, a) {    
  15.         return i == a.indexOf(itm);    
  16.     });    
  17.     $(uniqueGroup).each(function () {    
  18.         var Group = jQuery('<optgroup/>', { label: $(this)[0] }).appendTo(selectControl);    
  19.         var grpItems = $(selectControl).find('option[data-group="' + $(this)[0] + '"]');    
  20.         $(grpItems).each(function () {    
  21.             var item = $(this);    
  22.             item.appendTo(Group);    
  23.         });    
  24.     });    
  25. }    
  26. </script>
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!this.IsPostBack)  
  4.     {  
  5.         string str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;  
  6.         SqlConnection conn = new SqlConnection(str);  
  7.         conn.Open();  
  8.         SqlCommand cmd = new SqlCommand("SELECT EmployeeID,FirstName,TitleOfCourtesy FROM Employees", conn);  
  9.         SqlDataAdapter da = new SqlDataAdapter(cmd);  
  10.         DataTable dt = new DataTable();  
  11.         da.Fill(dt);  
  12.         foreach (DataRow row in dt.Rows)  
  13.         {  
  14.             ListItem item = new ListItem();  
  15.             item.Text = row["FirstName"].ToString();  
  16.             item.Value = row["EmployeeID"].ToString();  
  17.             item.Attributes["data-group"] = row["TitleOfCourtesy"].ToString();  
  18.             ddlNames.Items.Add(item);  
  19.         }  
  20.         conn.Close();  
  21.     }  
  22. }  
 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. 
 

Answers (1)