Click here to Skip to main content
15,881,173 members
Articles / Programming Languages / C#
Tip/Trick

KeyValuePairTextBox which Saves Data Key Value pair

Rate me:
Please Sign up or sign in to vote.
4.50/5 (3 votes)
20 Mar 2011CPOL2 min read 17.7K   2   1
KeyValuePairTextBox which Saves Data Key Value pair
KeyValuePair TextBox is an extended textbox which saves data Key Value pair. That means, If you have Product name shown in textbox. then you can also associate Product ID, without using any hidden variable or other control. This Idea came to me while doing a perfomance improvement on one of the projects. This control can be very useful when you do not want the dropdown list to be loaded on the page at the beginning and you want on demand population. For example, the user will see only product Name and when he presses enters on textbox, a Popup populates with other product and allows the user to choose a product. User can choose its product and you can store its respective ProductID in "TextValue" field of TextBox.

The best part of KeyValuePair TextBox is both the properties "Text" and "TextValue" can be changed through JavaScript and posted to the server. KeyValuePairTextBox modifies the name tag of HTML TextBox control and appends the corresponding Value with a seperator '$'.



How it Works


The biggest challenge while extending Textbox property was that the properties should be managed with JavaScript. Following were the issues while developing such control:

  1. Browser does not recognize the custom properties on control, so they are not part of Post variables.
  2. If value is set from server side code, it will be part of ViewState, which cannot be handled in JavaScript.

So after sometime I realized, when we post a form to server it sends form data in keyValuePair. So normal Textbox data is send as "&txtTestBox1=hello"

I thought of manupulating the value, so I decided to append my text value in key, which is the name of the control


This JavaScript code does the trick:


JavaScript
 <script language="'javascript'"> 
 
function setTextValue(ctrl,val)	{
ctrl.name=ctrl.id+"$"+val;
 
}
</script>

The above JavaScript method will set the TextValue property of control. The sample code demonstrates the use of the above JavaScript.

So when we post data on server, we get key name with TextValue.



Let's do the implementation step by step:



  1. Start a new C# Class Library Project ARLib
  2. Add a class to it called KeyValuePairTextBox.cs
  3. Paste the code below to the KeyValuePairTextBox.cs file:
  4. C#
    //
    // CustomTestBox.KeyValuePairTextBox.cs
    //
    // Authors:
    //	Pallav Sharma (ballubro@gmail.com)
    // 
    //This TextBox store Text and Value for the text, Like Product and ProductID
    //
     
    using System;
    using System.Web;
    using System.Web.UI;
    using System.ComponentModel;
    using System.Security.Permissions;
    namespace CustomTestBox
    {
        [AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        [AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
        public class KeyValuePairTextBox : System.Web.UI.WebControls.TextBox 
        {
            /// <summary>
            /// 
            /// </summary>
            [Bindable(true)]
            [Category("Appearance")]
            [DefaultValue("")]       
            public string TextValue
            {
                get
                {
                   String s = (String)ViewState["TextValue"];
                   return ((s == null) ? "" : s);
                }
                set
                {                
                    ViewState["TextValue"] = value;
                }
            }
     
            /// <summary>
            /// 
            /// </summary>
            /// <param name="writer"></param>
            protected override void Render(System.Web.UI.HtmlTextWriter writer)
            {            
                Page.ClientScript.RegisterStartupScript(this.GetType(),"SetValue","function 
     
    setTextValue(ctrl,val){ctrl.name=ctrl.id+\"$\"+val;}",true);
                if (!String.IsNullOrEmpty(this.TextValue))
                {                
                    writer.AddAttribute(HtmlTextWriterAttribute.Name, this.ClientID + "$" + this.TextValue);
                }
                writer.AddAttribute("TextValue", this.TextValue);
                base.Render(writer);
            }
     
            /// <summary>
            /// 
            /// </summary>
            protected override void TrackViewState()
            {
                String textValue = GetValueFromKey(this.ID, '$');
                if (!String.IsNullOrEmpty(textValue))
                    this.TextValue = textValue;
     
                if (HttpContext.Current.Request.Form["__EVENTTARGET"] == this.ClientID)
                {
                    RaisePostDataChangedEvent();
                }
                //If Enable, old viewstate data is getting saved
                //base.TrackViewState();         
            }     
      
           /// <summary>
           /// Get the value from Request.From Keys collection for given control ID 
           /// </summary>
           /// <param name="controlID">control's ClientID </param>
           /// <param name="separator">seprator used in key for seprating value</param>
           /// <returns>value</returns>
           private string GetValueFromKey(string controlClientID, char separator)
           {
               String[] allKeys = HttpContext.Current.Request.Form.AllKeys;
               String[] values = { };
               String value = String.Empty;
               foreach (String key in allKeys)
               {
                   if (key.Contains(controlClientID + separator.ToString()))
                   {
                       values = key.Split(separator);                   
                       this.Text = HttpContext.Current.Request.Form[key];
                       value = values[values.Length - 1];
                       break;
                   }              
               }
               return value;
           }
            /// <summary>
            /// 
            /// </summary>
           protected override void RaisePostDataChangedEvent()
           {
               OnTextChanged(EventArgs.Empty);           
           }
            /// <summary>
            /// 
            /// </summary>
           public static readonly object TextChangedEvent = new object();
            /// <summary>
            /// 
            /// </summary>
            /// <param name="e"></param>
           protected new void OnTextChanged(EventArgs e)
           {
               EventHandler h = (EventHandler)Events[TextChangedEvent];
               if (h != null)
                   h(this, e);
           } 
            /// <summary>
            /// 
            /// </summary>
           [Category("Action")]
           public new event EventHandler TextChanged
           {
               add { Events.AddHandler(TextChangedEvent, value); }
               remove { Events.RemoveHandler(TextChangedEvent, value); }
           }      
        }
    }

  5. Compile the library
  6. Drag and Drop Control from toolbox
  7. Set the Text and TextValue Property

  8. <cc1:KeyValuePairTextBox ID="txtKeyValue1" runat="server" EnableViewState="true" 
                onchange="setTextValue(this,'myValueByJavaScript1');" Text="Hello" TextValue="World" ></cc1:KeyValuePairTextBox>

  9. Done!

You can change the TextValue Property through JavaScript by calling the setTextValue(ctrl,val) method. Hope this helps..

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) ITC Infotech India Ltd.
India India
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

 
GeneralReason for my vote of 4 Very helpful Pin
Member 220417516-Mar-11 21:17
Member 220417516-Mar-11 21:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.