Click here to Skip to main content
15,887,344 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello,

I'm trying to fill a dropdownlist having the data in groups, in a content page. I'm using the Northwind Database. Here's my code:

SQL Server
SQL
CREATE PROCEDURE EmployeesSelect
AS
BEGIN
	SET NOCOUNT ON;

	SELECT EmployeeID,FirstName,TitleOfCourtesy 
	FROM dbo.Employees
END
GO

HTML
ASP.NET
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <asp:DropDownList ID="ddlNames" runat="server"></asp:DropDownList>
    <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>
    
</asp:Content>

C#
C#
protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                ddlNames.Items.Clear();
                ddlNames.Items.Add(new ListItem("", "0"));

                ddlNames.AppendDataBoundItems = true;

                string str = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                SqlConnection conn = new SqlConnection(str);
                conn.Open();
                SqlCommand sqlCmd = new SqlCommand("dbo.EmployeesSelect", conn);
                SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
                sqlCmd.CommandType = CommandType.StoredProcedure;
                DataTable dt = new DataTable();
                sqlDa.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();
            }
        }

Even though the code works in a single page, I cannot get the data in groups when I use it in a master/content page.

Any kind of help would be appreciated.

What I have tried:

1. Created a .js and added the function, imported the .js file to the master page.
Posted
Updated 19-Apr-18 10:24am
v3
Comments
F-ES Sitecore 19-Apr-18 4:28am    
Your code relies on data and file structures that we can't access so no-one can debug this for you, you're going to have to learn some debugging yourself.

If it works on a normal page but not master\content then the likely issues are control ids and paths to js files. Your dropdown seems to hold a list of control ids, but are those ids correct? Do controls with those ids actually exist on the page? And I mean in the html source when your js is running, not in your aspx file.

Look for error messages in the browser console and use the "debugger" statement to step through your js line by line and try and get an idea about what isn't working, eg does thise line return a value?

var selectControl = $('#' + id);

and so on.

Either write the Javascript on a master page or Register the script from the code behind using ClientScriptManager class. More information about client script manager here.
 
Share this answer
 
Comments
Chriz12 20-Apr-18 5:24am    
Thank you for the answer,I tried both your suggestions but I still get the results without the grouping.
You're using a master page, so the IDs of the controls on the content page will be "mangled". If you view the rendered source of the page, you'll see that there is no element with the ID "ddlNames".

You have two choices:

1) Add ClientIDMode="Static" to your control:
<asp:DropDownList ID="ddlNames" runat="server" ClientIDMode="Static"></asp:DropDownList>
Control.ClientIDMode Property (System.Web.UI)[^]

2) Inject the ClientID property into the script:
<asp:DropDownList ID="ddlNames" runat="server"></asp:DropDownList>

<script type="text/javascript">
$(function () {    
    GroupDropdownlist('<%= ddlNames.ClientID %>');
});
NB: This only works if the script is declared inline. If you move the script to an external .js file, it won't work.
 
Share this answer
 
Comments
Chriz12 20-Apr-18 5:27am    
Thank you for the reply, I changed the code as suggested and now I get both Names and TitleOfCourtesy in the same level of dropdownlist instead of grouping Names based on TitleOfCourtesy (with no choice of selecting TitleoOfCourtesy though)

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