locked
Creating a Composite Control RRS feed

  • Question

  • User-564099267 posted
    using System;
    using System.ComponentModel;
    using System.Data;
    using System.Security.Permissions;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Drawing.Design;
    using UVNET;
    
    namespace RTG.SiteTools.WebControls {
        [System.Web.AspNetHostingPermission(System.Security.Permissions.SecurityAction.Demand, Level = System.Web.AspNetHostingPermissionLevel.Minimal),
         System.Web.AspNetHostingPermission(System.Security.Permissions.SecurityAction.InheritanceDemand, Level = System.Web.AspNetHostingPermissionLevel.Minimal),
         Designer("System.Web.UI.Design.WebControls.ListControlDesigner, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
         DataBindingHandler("System.Web.UI.Design.WebControls.ListControlDataBindingHandler, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"),
         ParseChildren(true, "Items"), ControlValueProperty("SelectedValue"),
         ToolboxData("<{0}:DropdownList runat=server ID=DropdownList1></{0}:DropdownList>")]
        public class DropdownList : CompositeControl {
            public enum Case { Capitalize, LowerCase, UpperCase }
            public enum ContextMenuOptions { Capitalize, LowerCase, UpperCase }
    
            private System.Web.UI.WebControls.DropDownList _ddl;
            private RequiredFieldValidator _validator;
            private AjaxControlToolkit.ListSearchExtender _searchList;
            private RTG.SiteTools.WebControls.Textbox _txt;
            private System.Web.UI.WebControls.Button _btn;
    
            #region Extended Properties
    
            public bool HasValidation { get; set; }
            public bool SearchControl { get; set; }
    
            
            public string Fields { get; set; }
            public string TextField { get; set; }
            public Case TextCase { get; set; }
            public string ValueField { get; set; }
            public string FileName { get; set; }
            public string RecordName { get; set; }
            public bool HasDescription { get; set; }
            public string SeperatorSymbol { get; set; }
            public bool Sort { get; set; }
            public string onblur { get; set; }
            public string onfocus { get; set; }
    
            private string MenuRec {
                get {
                    if (ViewState["MenuRec"] == null) {
                        return "";
                    } return ViewState["MenuRec"].ToString();
                }
                set { ViewState["MenuRec"] = value; }
            }
    
            private string imgAdd {
                get {
                    if (ViewState["imgAdd"] == null) {
                        string img = Page.ClientScript.GetWebResourceUrl(this.GetType(), "RTG.SiteTools.WebControls.Images.plus.png");
                        ViewState["imgAdd"] = img;
                        return img;
                    } else {
                        return ViewState["imgAdd"].ToString();
                    }
                }
                set { ViewState["imgAdd"] = value; }
            }
            private string imgEdit {
                get {
                    if (ViewState["imgEdit"] == null) {
                        string img = Page.ClientScript.GetWebResourceUrl(this.GetType(), "RTG.SiteTools.WebControls.Images.edit2.png");
                        ViewState["imgEdit"] = img;
                        return img;
                    } else {
                        return ViewState["imgEdit"].ToString();
                    }
                }
                set { ViewState["imgEdit"] = value; }
            }
            private string imgDelete {
                get {
                    if (ViewState["imgDelete"] == null) {
                        string img = Page.ClientScript.GetWebResourceUrl(this.GetType(), "RTG.SiteTools.WebControls.Images.delete.png");
                        ViewState["imgDelete"] = img;
                        return img;
                    } else {
                        return ViewState["imgDelete"].ToString();
                    }
                }
                set { ViewState["imgDelete"] = value; }
            }
    
            #endregion Extended Properties
    
    
            #region DropdownList
    
            [Bindable(true), Category("Appearance"), DefaultValue(true), Description("The dropdown control")]
            public System.Web.UI.WebControls.DropDownList DDList {
                get { EnsureChildControls(); return _ddl; }
                set { EnsureChildControls(); _ddl = value; }
            }
    
            [Bindable(true), Category("Behavior"), DefaultValue(true), Description("")]
            public bool CausesValidation {
                get { EnsureChildControls(); return _ddl.CausesValidation; }
                set { EnsureChildControls(); _ddl.CausesValidation = value; }
            }
    
            public bool AutoPostBack {
                get { return _ddl.AutoPostBack; }
                set { _ddl.AutoPostBack = value; }
            }
    
            [Bindable(true), Category("Appearance"), DefaultValue(""), Description("Sets the class of the Css for the valadator.")]
            public override string CssClass {
                get { EnsureChildControls(); return _ddl.CssClass; }
                set { EnsureChildControls(); _ddl.CssClass = " " + value; }
            }
    
            
    
            [Bindable(true), Category("Appearance"), DefaultValue(""), Description("Gets or Sets the selected Text of the dropdown Control")]
            public string Text {
                get { EnsureChildControls(); return _ddl.Text; }
                set { EnsureChildControls(); _ddl.Text = value; }
            }
    
            [PersistenceMode(PersistenceMode.InnerDefaultProperty), Description("List Collection of Tools")]
            public virtual ListItemCollection Items {
                get {
                    if (ViewState["ddlListItems"] == null) {
                        return new ListItemCollection();
                    } else {
                        return (ListItemCollection)ViewState["ddlListItems"];
                    }
                }
                set { ViewState["ddlListItems"] = value; }
            }
    
            [Bindable(true), Category("Validation"), DefaultValue(""), Description("Sets the validation group name")]
            public string ValidationGroup {
                get { EnsureChildControls(); return _ddl.ValidationGroup; }
                set { EnsureChildControls(); _ddl.ValidationGroup = value; _validator.ValidationGroup = value; }
            }
    
            #endregion DropdownList
    
            #region Field Validator
    
            [Bindable(true), Category("Appearance"), DefaultValue(""), Description("Sets the Error message if selection is empty")]
            public string RequiredMessage {
                get { EnsureChildControls(); return _validator.ErrorMessage; }
                set { EnsureChildControls(); _validator.ErrorMessage = value; }
            }
    
            [Bindable(true), Category("Appearance"), DefaultValue("required"), Description("Sets the class of the Css for the valadator.")]
            public string RequiredCssClass {
                get { EnsureChildControls(); return _validator.CssClass; }
                set { EnsureChildControls(); _validator.CssClass = value; }
            }
    
    
    
            #endregion Field Validator
    
    
            #region Search Extender
    
            [Bindable(true), Category("Appearance"), DefaultValue("hidePrompt"), Description("Sets the class of the Css for the valadator.")]
            public string PromptCssClass {
                get { EnsureChildControls(); return _searchList.PromptCssClass; }
                set { EnsureChildControls(); _searchList.PromptCssClass = value; }
            }
    
            #endregion Search Extender
    
    
            #region Events
    
            private static readonly object EventSubmitKey = new object();
    
            // handles the click event of the LinkButton
            [Category("Action"), Description("Raised when the user changes the selected index")]
            public event EventHandler SelectedIndexChanged {
                add { Events.AddHandler(EventSubmitKey, value); }
                remove { Events.RemoveHandler(EventSubmitKey, value); }
            }
    
            protected virtual void OnSelectedIndex_Changed(EventArgs e) {
                EventHandler SubmitHandler = (EventHandler)Events[EventSubmitKey];
                if (SubmitHandler != null) { SubmitHandler(this, e); }
            }
    
            private void _SelectedIndex_Changed(object source, EventArgs e) {
                OnSelectedIndex_Changed(EventArgs.Empty);
            }
    
            protected void _btn_Click(object sender, EventArgs e) {
                System.Diagnostics.Debugger.Break();
            }
    
    
            #endregion Events
            
    
            protected override void OnInit(EventArgs e) {
                Type t = this.GetType();
                base.OnInit(e);
                EnsureChildControls();
                DivisionChanged("", t);
    
                if (!Page.ClientScript.IsClientScriptIncludeRegistered(t, "jqueryjs")) {
                    string url = Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.js.jQuery.js");
                    Page.ClientScript.RegisterClientScriptInclude(t, "jqueryjs", url);
                }
    
                if (!Page.ClientScript.IsClientScriptIncludeRegistered(t, "webControlsJs")) {
                    string url = Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.js.WebControls.js");
                    Page.ClientScript.RegisterClientScriptInclude(t, "webControlsJs", url);
                }
    
                if (!Page.ClientScript.IsClientScriptIncludeRegistered(t, "contextMenujs")) {
                    string url = Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.js.ContextMenu.js");
                    Page.ClientScript.RegisterClientScriptInclude(t, "contextMenujs", url);
                }
    
                _ddl.DataSource = CreateDataSource();
    
                if (String.IsNullOrEmpty(TextField)) { _ddl.DataTextField = "Text"; }
                else { _ddl.DataTextField = TextField; }
                if (!String.IsNullOrEmpty(ValueField)) { _ddl.DataValueField = ValueField; }
    
                switch (TextCase) {
                    case Case.Capitalize:
                        _ddl.CssClass = "ddl";
                        break;
                    case Case.LowerCase:
                        _ddl.CssClass = "ddlLower";
                        break;
                    case Case.UpperCase:
                        _ddl.CssClass = "ddlUpper";
                        break;
                    default:
                        _ddl.CssClass = "ddl";
                        break;
                }
    
                onfocus += "TextBox_FocusChaged(this, event, 'selected" + _ddl.CssClass + "');" + onfocus;
                onblur += "TextBox_FocusChaged(this, event, '" + _ddl.CssClass + "');" + onblur;
                _ddl.Attributes.Add("onfocus", onfocus);
                _ddl.Attributes.Add("onblur", onblur);
    
                try {
                    _ddl.DataBind();
                } catch {
    
                }
    
                foreach (ListItem item in Items) {
                    _ddl.Items.Add(item);
                }
    
            }
    
            protected System.Collections.ICollection CreateDataSource() {
                DataTable dt = new DataTable();
                DataView dv;
                if (String.IsNullOrEmpty(TextField)) { TextField ="Text";}
    
                dt.Columns.Add(new DataColumn(TextField, typeof(String)));
    
                if (!String.IsNullOrEmpty(ValueField)) {
                    dt.Columns.Add(new DataColumn(ValueField, typeof(String)));
                }
    
                if (String.IsNullOrEmpty(Fields)) {
                    Fields = "1";
                }
    
                int[] j = new int[Fields.Split(';').Length];
                for (int a = 0; a < Fields.Split(';').Length; a++) {
                    j[a] = Convert.ToInt32(Fields.Split(';')[a]);
                }
    
                if (j.Length > 0 && j.Length < 4) {
                    string[] n = GetRecs(FileName, RecordName, j);
    
                    if (n == null) {
                        dt.Rows.Add(CreateRow("No Recs Found", dt));
                        dv = new DataView(dt);
                        return dv;
                    }
    
                    if (j.Length == 1) {
                        dt.Rows.Add(CreateRow("", dt));
                        if (String.IsNullOrEmpty(RecordName)) {
                            for (int i = 0; i < n.Length; i++) {
                                dt.Rows.Add(CreateRow(n[i], dt));
                            }
                        } else {
                            for (int i = 0; i < n[0].Split(UVNET.UniArray.vm).Length; i++) {
                                dt.Rows.Add(CreateRow(n[0].Split(UVNET.UniArray.vm)[i], dt));
                            }
                        }
                       
                    } else if (HasDescription && j.Length == 2) {
                        dt.Rows.Add(CreateRow("", dt));
                        if (String.IsNullOrEmpty(SeperatorSymbol)) {
                            SeperatorSymbol = " - ";
                        }
                        for (int i = 0; i < n[0].Split(UVNET.UniArray.vm).Length; i++) {
                            dt.Rows.Add(CreateRow(n[0].Split(UVNET.UniArray.vm)[i] + SeperatorSymbol + n[1].Split(UVNET.UniArray.vm)[i], dt));
                        }
                    } else if (!HasDescription && j.Length == 2) {
                        dt.Rows.Add(CreateRow("", "", dt));
                        for (int i = 0; i < n[0].Split(UVNET.UniArray.vm).Length; i++) {
                            dt.Rows.Add(CreateRow(n[0].Split(UVNET.UniArray.vm)[i], n[1].Split(UVNET.UniArray.vm)[i], dt));
                        }
                       
                    } else if (j.Length == 3) {
                        dt.Rows.Add(CreateRow("", "", dt));
                        for (int i = 0; i < n[0].Split(UVNET.UniArray.vm).Length; i++) {
                            dt.Rows.Add(CreateRow(n[0].Split(UVNET.UniArray.vm)[i] + SeperatorSymbol + n[2].Split(UVNET.UniArray.vm)[i], n[1].Split(UVNET.UniArray.vm)[i], dt));
                        }
                       
    
                    }
                } else {
                    dt.Rows.Add(CreateRow("", "Invalid Field Length", dt));
                }
    
    
    
                dv = new DataView(dt);
                if (Sort) {
                    if (String.IsNullOrEmpty(TextField)) {
                        dv.Sort = "Text";
                    } else {
                        dv.Sort = TextField;
                    }
    
                }
                return dv;
            }
    
            private string[] GetRecs(string FileName, string RecordName, int[] j) {
                if (String.IsNullOrEmpty(FileName)) { return new string[] { }; }
                if (System.Web.HttpContext.Current.Session["UONET_Info"] == null) { return new string[] { }; }
                UVNET.UONET uoNet = (UVNET.UONET)System.Web.HttpContext.Current.Session["UONET_Info"];
                string rec = "";
                if (FileName.ToUpper() != "BP") {
                    if (!String.IsNullOrEmpty(RecordName)) {
                        string[] n = new string[j.Length];
    
                        rec = uoNet.Read(FileName, RecordName);
                        if (String.IsNullOrEmpty(rec)) { return new string[] { }; }
    
                        string[] cfBuyersInitRec = rec.Split(UVNET.UniArray.fm);
                        if (cfBuyersInitRec.Length < 1) { return new string[] { }; }
    
                        for (int a = 0; a < j.Length; a++) {
                            if (cfBuyersInitRec.Length < j[a] - 1) { return null; }
                            n[a] = cfBuyersInitRec[j[a] - 1].ToLower();
                        }
    
                        uoNet.CloseFile(FileName);
                        return n;
                    } else {
                        string[] ids;
                        string str = "SELECT " + FileName;
                        if (uoNet.Execute(str, out rec) <= 0) { return new string[] { }; }
                        ids = uoNet.ReadList();
                        return ids;
                    }
                } else {
                    if (!String.IsNullOrEmpty(RecordName)) {
                        string[] recs = new string[] { "", "", "" };
                        uoNet.Subroutine(RecordName, ref recs);
                        return (new string[] { recs[1] });
                    }
                }
                return new string[] { "no recs found" };
            }
    
    
            protected DataRow CreateRow(String Value, String Text, DataTable dt) {
                DataRow dr = dt.NewRow();
                dr[0] = Value.ToLower().Trim();
    
                switch (TextCase) {
                    case Case.Capitalize:
                        dr[1] = Text.ToTitleCase(true);
                        break;
                    case Case.LowerCase:
                        dr[1] = Text.ToLower().Trim();
                        break;
                    case Case.UpperCase:
                        dr[1] = Text.ToUpper().Trim();
                        break;
                    default:
                        dr[1] = Text.ToLower().Trim();
                        break;
                }
                return dr;
            }
    
            protected DataRow CreateRow(String Text, DataTable dt) {
                DataRow dr = dt.NewRow();
    
                switch (TextCase) {
                    case Case.Capitalize:
                        dr[0] = Text.ToTitleCase(true);
                        break;
                    case Case.LowerCase:
                        dr[0] = Text.ToLower().Trim();
                        break;
                    case Case.UpperCase:
                        dr[0] = Text.ToUpper().Trim();
                        break;
                    default:
                        dr[0] = Text.ToLower().Trim();
                        break;
                }
    
    
    
                return dr;
            }
    
            public void DivisionChanged(string hostname, Type t) {
                //System.Diagnostics.Debugger.Break();
                if (String.IsNullOrEmpty(hostname)) {
                    if (System.Web.HttpContext.Current.Session["UONET_Info"] != null) {
                        hostname = ((UVNET.UONET)System.Web.HttpContext.Current.Session["UONET_Info"]).HostName.ToUpper().Replace("DEV", "");
                    } else {
                        hostname = "";
                    }
                }
    
                switch (hostname.ToLower()) {
                    case "rtg2":
                        if (!Page.ClientScript.IsClientScriptBlockRegistered(t, hostname + "rtg2txtcss")) {
                            string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.css.FL.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rtg2txtcss", css, false);
                        }
                        break;
                    case "rtg0":
                        if (!Page.ClientScript.IsClientScriptBlockRegistered(t, hostname + "rtg0txtcss")) {
                            string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.css.SE.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rtg0txtcss", css, false);
                        }
                        break;
                    case "rtg9":
                        if (!Page.ClientScript.IsClientScriptBlockRegistered(t, hostname + "rtg9txtcss")) {
                            string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.css.TX.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rtg9txtcss", css, false);
                        }
                        break;
                    case "rtg7":
                        if (!Page.ClientScript.IsClientScriptBlockRegistered(t, hostname + "rtg7txtcss")) {
                            string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.css.PR.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "rtg7txtcss", css, false);
                        }
                        break;
                    default:
                        if (!Page.ClientScript.IsClientScriptBlockRegistered(t, hostname + "txtcss")) {
                            string css = "<link href=\"" + Page.ClientScript.GetWebResourceUrl(t, "RTG.SiteTools.WebControls.css.FL.css") + "\" type=\"text/css\" rel=\"stylesheet\" />";
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "txtcss", css, false);
                        }
                        break;
                }
            }
    
            protected override void RecreateChildControls() { EnsureChildControls(); }
    
            protected override void CreateChildControls() {
                Controls.Clear();
    
                _ddl = new System.Web.UI.WebControls.DropDownList();
                _ddl.ID = this.ID + "_ddl";
                _ddl.SelectedIndexChanged += new EventHandler(_SelectedIndex_Changed);
                this.Controls.Add(_ddl);
                
                _validator = new RequiredFieldValidator();
                _validator.ID = "_validateDDL";
                _validator.Display = ValidatorDisplay.Dynamic;
                _validator.ControlToValidate = DDList.ID;
                this.Controls.Add(_validator);
    
                _searchList = new AjaxControlToolkit.ListSearchExtender();
                _searchList.ID = "_searchDDL";
                _searchList.TargetControlID = DDList.ID;
                this.Controls.Add(_searchList);
    
    
                _btn = new System.Web.UI.WebControls.Button();
                _btn.ID = this.ID + "_btn";
                _btn.Click += new EventHandler(_btn_Click);
                _btn.Style.Add("display", "inline");
                this.Controls.Add(_btn);
    
                _txt = new RTG.SiteTools.WebControls.Textbox();
                _txt.ID = this.ID + "_txt";
                _txt.Attributes.Add("onkeypress", "return clickButton(event,'" + _btn.ClientID + "')");
                _txt.Style.Add("display", "inline");
                this.Controls.Add(_txt);
    
    
            }
    
    
    
            protected override void Render(HtmlTextWriter writer) {
                AddAttributesToRender(writer);
    
    
                #region JavaScript for right click context Menu
    
    
                string[] actions = GetPermissions();
    
                // only build the context menu if user has action
              //  if (actions.Length > 0) {
                    Type t = this.GetType();
                    string jScript = "";
    
                    writer.Write("<script type=\"text/javascript\">");
    
                    writer.Write("var count = 1;");
                    writer.Write("var myMenu" + this.ID + " = [");
    
                    Page.ClientScript.GetWebResourceUrl(this.GetType(), "RTG.SiteTools.WebControls.Images.Tools.ClearData.png");
    
              //      if (actions.Contains("ADD") > -1) {
                    jScript += "{'Add'   : { onclick: function () {ToggleContols('" + _ddl.UniqueID + "', '" + _txt.UniqueID + "'); }, icon: '" + imgAdd + "'  }},";
              //      }
              //      if (actions.Contains("EDIT") > -1) {
                        jScript += "{'Edit'  : { onclick: function () { }, icon: '"  + imgEdit   +  "' }},";
              //      }
              //      if (actions.Contains("DELETE") > -1) {
                        jScript += "{'Delete': { onclick: function () { }, icon: '"  + imgDelete +  "'}},";
              //      }
    
                    writer.Write(jScript.RemoveLastChar(','));
    
                    writer.Write("];");
    
                    writer.Write("var beforeShowFunc = function() { var $menu = this.menu; $menu.find('.option-count').html(count++); }; ");
    
                    writer.Write("$(function() { $('.contextMenu" + this.ID + "').contextMenu(myMenu" + this.ID + " ,{beforeShow:beforeShowFunc}); });");
    
                    writer.Write("</script>");
    
              //  }
    
    
    
    
                #endregion JavaScript for right click context Menu
    
                       
    
    
                    writer.Write("<div class=\"example-show\" style=\"display:inline;\">");
                    writer.Write("<div class=\"contextMenu" + this.ID + "\" style=\"display:inline;\">");
    
                    
    
                _ddl.RenderControl(writer);
                _txt.RenderControl(writer);
                _btn.RenderControl(writer);
                
                if (HasValidation) {
                    writer.Write("&nbsp;<b id=\"validatorSymbol\" class=\"required\">*</b>&nbsp;");
                    _validator.RenderControl(writer);
                }
                if (SearchControl) {
                    _searchList.BehaviorID = _searchList.UniqueID;
                    _searchList.RenderControl(writer);
                }
    
                
                    writer.Write("</div>");
                    writer.Write("</div>");
            }
    
            public string[] GetPermissions() {
                string[] actions = new string[] { };
    
                if (System.Web.HttpContext.Current.Session["UONET_Info"] != null) {
                    UVNET.UONET uoNet = (UVNET.UONET)System.Web.HttpContext.Current.Session["UONET_Info"];
    
                    if (String.IsNullOrEmpty(MenuRec)) {
                        string[] location = HttpContext.Current.Request.RawUrl.Split('/').RemoveAt(new int[] { 0, 1 }).Replace(".aspx", "");
                        string recID = "", rec = "";
                        for (int j = 0; j < location.Length; j++) {
                            recID += (j + 1) == location.Length ? location[j].Split('?')[0].ToUpper() : location[j].ToUpper() + ".";
                        }
    
                        if (uoNet.Read("MENU.WIN", recID, out rec)) {
                            MenuRec = rec;
                        }
                    }
    
                    string[] editableControls = MenuRec.uExtract(4).Split(UniArray.vm);
    
                    int pos = editableControls.Contains(this.ID);
                    if (pos > -1) {
                        actions = MenuRec.uExtract(5, pos).Split(UVNET.UniArray.sm);
    
                        for(int j = 0; j < actions.Length; j++){
                            string[] editalUsers = MenuRec.uExtract(6, pos, j).Split((char)251);
                            if(editalUsers.Contains(uoNet.UserName) < 0) {
                                actions = actions.RemoveAt(new int[] {j});
                            }
                        }
                        return actions;
                    }
                }
                return new string[]{};
            }
    
        }
    }
    
    

    // javascript / jquery

    /**
    * jquery.contextmenu.js
    * jQuery Plugin for Context Menus
    * http://www.JavascriptToolbox.com/lib/contextmenu/
    *
    * Copyright (c) 2008 Matt Kruse (javascripttoolbox.com)
    * Dual licensed under the MIT and GPL licenses. 
    
    */
    ; (function ($) {
        $.contextMenu = {
            //        shadow: true,
            //        shadowOffset: 0,
            //        shadowOffsetX: 5,
            //        shadowOffsetY: 5,
            //        shadowWidthAdjust: -3,
            //        shadowHeightAdjust: -3,
            //        shadowOpacity: .2,
            //        shadowClass: 'context-menu-shadow',
            //        shadowColor: 'black',
    
            offsetX: 0,
            offsetY: 0,
            appendTo: 'body',
            direction: 'down',
            constrainToScreen: true,
    
            showTransition: 'show',
            hideTransition: 'hide',
            showSpeed: null,
            hideSpeed: null,
            showCallback: null,
            hideCallback: null,
    
            className: 'context-menu',
            itemClassName: 'context-menu-item',
            itemHoverClassName: 'context-menu-item-hover',
            disabledItemClassName: 'context-menu-item-disabled',
            disabledItemHoverClassName: 'context-menu-item-disabled-hover',
            separatorClassName: 'context-menu-separator',
            innerDivClassName: 'context-menu-item-inner',
            themePrefix: 'context-menu-theme-',
            theme: 'default',
    
            separator: 'context-menu-separator', // A specific key to identify a separator
            target: null, // The target of the context click, to be populated when triggered
            menu: null, // The jQuery object containing the HTML object that is the menu itself
            shadowObj: null, // Shadow object
            bgiframe: null, // The iframe object for IE6
            shown: false, // Currently being shown?
            useIframe: /*@cc_on@*//*@if (@_win32)true, @else @*/false,/*@end@*/ // This is a better check than looking at userAgent!
    
            // Create the menu instance
            create: function (menu, opts) {
                var cmenu = $.extend({}, this, opts); // Clone all default properties to created object
    
                // If a selector has been passed in, then use that as the menu
                if (typeof menu == "string") {
                    cmenu.menu = $(menu);
                }
                // If a function has been passed in, call it each time the menu is shown to create the menu
                else if (typeof menu == "function") {
                    cmenu.menuFunction = menu;
                }
                // Otherwise parse the Array passed in
                else {
                    cmenu.menu = cmenu.createMenu(menu, cmenu);
                }
                if (cmenu.menu) {
                    cmenu.menu.css({ display: 'none' });
                    $(cmenu.appendTo).append(cmenu.menu);
                }
    
                // Create the shadow object if shadow is enabled
                if (cmenu.shadow) {
                    cmenu.createShadow(cmenu); // Extracted to method for extensibility
                    if (cmenu.shadowOffset) { cmenu.shadowOffsetX = cmenu.shadowOffsetY = cmenu.shadowOffset; }
                }
                $('body').bind('contextmenu', function () { cmenu.hide(); }); // If right-clicked somewhere else in the document, hide this menu
                return cmenu;
            },
    
            // Create an iframe object to go behind the menu
            createIframe: function () {
                return $('<iframe frameborder="0" tabindex="-1" src="javascript:false" style="display:block;;z-index:-1;filter:Alpha(Opacity=0);"/>');
            },
    
            // Accept an Array representing a menu structure and turn it into HTML
            createMenu: function (menu, cmenu) {
                var className = cmenu.className;
                $.each(cmenu.theme.split(","), function (i, n) { className += ' ' + cmenu.themePrefix + n });
                var $t = $('<table cellspacing=0 cellpadding=0></table>').click(function () { cmenu.hide(); return false; }); // We wrap a table around it so width can be flexible
                var $tr = $('<tr></tr>');
                var $td = $('<td></td>');
                var $div = $('<div class="' + className + '" style="padding:5px 0;"></div>');
    
                // Each menu item is specified as either:
                //     title:function
                // or  title: { property:value ... }
                for (var i = 0; i < menu.length; i++) {
                    var m = menu[i];
                    if (m == $.contextMenu.separator) {
                        $div.append(cmenu.createSeparator());
                    }
                    else {
                        for (var opt in menu[i]) {
                            $div.append(cmenu.createMenuItem(opt, menu[i][opt])); // Extracted to method for extensibility
                        }
                    }
                }
                if (cmenu.useIframe) {
                    $td.append(cmenu.createIframe());
                }
                $t.append($tr.append($td.append($div)))
                return $t;
            },
    
            // Create an individual menu item
            createMenuItem: function (label, obj) {
                var cmenu = this;
                if (typeof obj == "function") { obj = { onclick: obj }; } // If passed a simple function, turn it into a property of an object
                // Default properties, extended in case properties are passed
                var o = $.extend({
                    onclick: function () { },
                    className: '',
                    hoverClassName: cmenu.itemHoverClassName,
                    icon: '',
                    disabled: false,
                    title: '',
                    hoverItem: cmenu.hoverItem,
                    hoverItemOut: cmenu.hoverItemOut
                }, obj);
                // If an icon is specified, hard-code the background-image style. Themes that don't show images should take this into account in their CSS
                var iconStyle = (o.icon) ? 'background-image:url(' + o.icon + ');' : '';
                var $div = $('<div class="' + cmenu.itemClassName + ' ' + o.className + ((o.disabled) ? ' ' + cmenu.disabledItemClassName : '') + '" title="' + o.title + '"></div>')
                // If the item is disabled, don't do anything when it is clicked
                  .click(function (e) { if (cmenu.isItemDisabled(this)) { return false; } else { return o.onclick.call(cmenu.target, this, cmenu, e) } })
                // Change the class of the item when hovered over
                  .hover(function () { o.hoverItem.call(this, (cmenu.isItemDisabled(this)) ? cmenu.disabledItemHoverClassName : o.hoverClassName); }
                      , function () { o.hoverItemOut.call(this, (cmenu.isItemDisabled(this)) ? cmenu.disabledItemHoverClassName : o.hoverClassName); }
                  );
                var $idiv = $('<div class="' + cmenu.innerDivClassName + '" style="' + iconStyle + '">' + label + '</div>');
                $div.append($idiv);
                return $div;
            },
    
            // Create a separator row
            createSeparator: function () {
                return $('<div class="' + this.separatorClassName + '"></div>');
            },
    
            // Determine if an individual item is currently disabled. This is called each time the item is hovered or clicked because the disabled status may change at any time
            isItemDisabled: function (item) { return $(item).is('.' + this.disabledItemClassName); },
    
            // Functions to fire on hover. Extracted to methods for extensibility
            hoverItem: function (c) { $(this).addClass(c); },
            hoverItemOut: function (c) { $(this).removeClass(c); },
    
            // Create the shadow object
            createShadow: function (cmenu) {
                cmenu.shadowObj = $('<div class="' + cmenu.shadowClass + '"></div>').css({ display: 'none', position: "absolute", zIndex: 9998, opacity: cmenu.shadowOpacity, backgroundColor: cmenu.shadowColor });
                $(cmenu.appendTo).append(cmenu.shadowObj);
            },
    
            // Display the shadow object, given the position of the menu itself
            showShadow: function (x, y, e) {
                var cmenu = this;
                if (cmenu.shadow) {
                    cmenu.shadowObj.css({
                        width: (cmenu.menu.width() + cmenu.shadowWidthAdjust) + "px",
                        height: (cmenu.menu.height() + cmenu.shadowHeightAdjust) + "px",
                        top: (y + cmenu.shadowOffsetY) + "px",
                        left: (x + cmenu.shadowOffsetX) + "px"
                    }).addClass(cmenu.shadowClass)[cmenu.showTransition](cmenu.showSpeed);
                }
            },
    
            // A hook to call before the menu is shown, in case special processing needs to be done.
            // Return false to cancel the default show operation
            beforeShow: function () { return true; },
    
            // Show the context menu
            show: function (t, e) {
                var cmenu = this, x = e.pageX, y = e.pageY;
                cmenu.target = t; // Preserve the object that triggered this context menu so menu item click methods can see it
                if (cmenu.beforeShow() !== false) {
                    // If the menu content is a function, call it to populate the menu each time it is displayed
                    if (cmenu.menuFunction) {
                        if (cmenu.menu) { $(cmenu.menu).remove(); }
                        cmenu.menu = cmenu.createMenu(cmenu.menuFunction(cmenu, t), cmenu);
                        cmenu.menu.css({ display: 'none' });
                        $(cmenu.appendTo).append(cmenu.menu);
                    }
                    var $c = cmenu.menu;
                    x += cmenu.offsetX; y += cmenu.offsetY;
                    var pos = cmenu.getPosition(x, y, cmenu, e); // Extracted to method for extensibility
                    cmenu.showShadow(pos.x, pos.y, e);
                    // Resize the iframe if needed
                    if (cmenu.useIframe) {
                        $c.find('iframe').css({ width: $c.width() + cmenu.shadowOffsetX + cmenu.shadowWidthAdjust, height: $c.height() + cmenu.shadowOffsetY + cmenu.shadowHeightAdjust });
                    }
                    $c.css({ top: pos.y + "px", left: pos.x + "px", position: "absolute", zIndex: 999999 })[cmenu.showTransition](cmenu.showSpeed, ((cmenu.showCallback) ? function () { cmenu.showCallback.call(cmenu); } : null));
                    cmenu.shown = true;
                    $(document).one('click', null, function () { cmenu.hide() }); // Handle a single click to the document to hide the menu
                }
            },
    
            // Find the position where the menu should appear, given an x,y of the click event
            getPosition: function (clickX, clickY, cmenu, e) {
                var x = clickX + cmenu.offsetX;
                var y = clickY + cmenu.offsetY
                var h = $(cmenu.menu).height();
                var w = $(cmenu.menu).width();
                var dir = cmenu.direction;
                if (cmenu.constrainToScreen) {
                    var $w = $(window);
                    var wh = $w.height();
                    var ww = $w.width();
                    if (dir == "down" && (y + h - $w.scrollTop() > wh)) { dir = "up"; }
                    var maxRight = x + w - $w.scrollLeft();
                    if (maxRight > ww) { x -= (maxRight - ww); }
                }
                if (dir == "up") { y -= h; }
                return { 'x': x, 'y': y };
            },
    
            // Hide the menu, of course
            hide: function () {
                var cmenu = this;
                if (cmenu.shown) {
                    if (cmenu.iframe) { $(cmenu.iframe).hide(); }
                    if (cmenu.menu) { cmenu.menu[cmenu.hideTransition](cmenu.hideSpeed, ((cmenu.hideCallback) ? function () { cmenu.hideCallback.call(cmenu); } : null)); }
                    if (cmenu.shadow) { cmenu.shadowObj[cmenu.hideTransition](cmenu.hideSpeed); }
                }
                cmenu.shown = false;
            }
        };
    
        // This actually adds the .contextMenu() function to the jQuery namespace
        $.fn.contextMenu = function (menu, options) {
            var cmenu = $.contextMenu.create(menu, options);
            return this.each(function () {
                $(this).bind('contextmenu', function (e) { cmenu.show(this, e); return false; });
            });
        };
    })(jQuery);
    //////////////////////////////////////////////////////////////////////////////////////////////
    
    function ToggleContols(ddlID, txtID) {
        var ddl = document.getElementsByName(ddlID);
        var txt = document.getElementsByName(txtID);
    
        if (ddl.style.display == "inline") {
            ddl.style.display = "none";
            ddl.value = "0";
            txt.style.display = "inline";
    
        } else {
            ddl.style.display = "inline";
            txt.style.display = "none";
        }
    }



    // The Issues

    1).  In the page source after the control is rendered there is 2 ID's.  The first one is the ID of the Control itself the Second is the ID of the DropDown that is assigned in the CreateChildControls.  Why does the Dropdown have 2 ID's?

    2).  The Context Menu will not display if I put it in the UpdatePanel and set the Trigger up for asncyPostBack.  As I understand it has something to do with binding it to the jquery and it being recreated when the panel updates.  Somehow I need to bind it again to the jquery.  But I have not figured out how to do this yet. 

    3).  When ToggleContols is called from the contect menu the controls are undifined if I use document.getElementsByID.  Probably because there is to IDs for the dropdown control.  Also I notice that when I can get the control it is not a <Select> list or <input type=text> but it is the C# type, so none of the html attributes are available.

    4).  The validator does not validate until the postback, but I think I need to create a custom validator and let the RegEx do the work there.  (not as important)

    I am trying to give our users the ability to add, edit or remove the items in the dropdown box and update the database with the changes.  So if they click Add then the display of the dropdown would be none and the textbox would show.  The button will always be hidden.  I just have that so they can click enter in the textbox to update the control.  When they do then the textbox will hide and they dropDown will become visible again.

    I would really appreciate all the help I can get.  Thanks!

    Friday, December 14, 2012 11:34 AM

All replies

  • User-564099267 posted

    Still needing some Help!  Somebody Please!

    Thursday, December 20, 2012 11:34 AM