I'm creating a menu based on the user using the following code

            System.Text.StringBuilder sb = new StringBuilder();
            sb.AppendLine("<ul>");
            if (!Page.IsPostBack)
            {
                foreach (DataRow row in datatable.Rows)
                {

                     sb.AppendLine(String.Format("<li><a href= x.aspx?Name={0}&Short={1}&Long={2}></a></li>",
                     HttpUtility.UrlEncode(row["x_name"].ToString()),
                     HttpUtility.UrlEncode(row["x_short_name"].ToString()),
                     HttpUtility.UrlEncode(row["x_long_name"].ToString()),
                     row["x_short_name"].ToString()));

When the user selects an item from the menu the page is loaded using a querystring.
What i need to do is to give the item selected from the menu a class so that it can be set to active.

Not sure how to go about this. Thanks in advance

Hi

You can check your query string parameter to see if it matches one of the items in the list that is about to be appended to the StringBuilder and if it is, add the class attribute.

The following is an example that I created based on your concept, but will need modifying to meet your exact requirements:

    protected void Page_Load(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        sb.AppendLine("<ul>");
        if (!Page.IsPostBack)
        {
            foreach (DataRow row in datatable.Rows)
            {
                List<Object> stringArgs = new List<Object>() 
                {
                    HttpUtility.UrlEncode(row["x_name"].ToString()),
                    HttpUtility.UrlEncode(row["x_short_name"].ToString()),
                    HttpUtility.UrlEncode(row["x_long_name"].ToString())                   
                };
                if (Request.QueryString["Name"] != null && Request.QueryString["Name"].ToString() == HttpUtility.UrlEncode(row["x_name"].ToString()))
                {
                    string classString = " class=" + @"""yourclass""";
                    stringArgs.Add(classString);
                    sb.AppendLine(String.Format("<li><a href=x.aspx?Name={0}&Short={1}&Long={2}{3}>Click here</a></li>", stringArgs.ToArray()));
                }
                else
                {
                    sb.AppendLine(String.Format("<li><a href=x.aspx?Name={0}&Short={1}&Long={2}>Click here</a></li>", stringArgs.ToArray()));
                }
            }
            sb.AppendLine("</ul>");
            listDiv.InnerHtml = sb.ToString();
        }
    }

HTH

Thank you :) got it working.

Use jQuery

$("ul.nav > li a[href*='pageName']").parent("ul.nav > li").addClass("active");
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.