posted 7/3/2011 by Raghav Khunger
You might have enountered the autcomplete which appears by default on textboxes on forms. I was working with some textboxes(Password e.t.c) where I needed to disable the autocomplete. I did the same by setting the "autocomplete" property of textbox control from server side code. But then I decided to make a Custom server control for the same so that everytime I don't have to write the same line again and again. Below is the code of Custom server control.MyTextBox.cs (Custom control) code:
public class MyTextBox : TextBox { #region Properties /// <summary> /// Gets or sets a value indicating whether to disable autocomplete or not. /// </summary> /// <value><c>true</c> if to disable; otherwise, <c>false</c>.</value> public virtual bool DisableAutoComplete { get { object obj = ViewState["DisableAutoComplete"]; if (obj != null) return (bool)obj; return false; } set { ViewState["DisableAutoComplete"] = value; } } #endregion #region OnLoad /// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event. /// </summary> /// <param name="e">The <see cref="T:System.EventArgs"/> /// object that contains the event data.</param> protected override void OnLoad(EventArgs e) { if (!Page.IsPostBack) { if (DisableAutoComplete) this.Attributes.Add("autocomplete", "off"); } } #endregion }
As you can see above the custom control is inherited from TextBox class. In this control a new property is exposed with the name DisableAutoComplete and with the help of this code:
if (DisableAutoComplete) this.Attributes.Add("autocomplete", "off");
in the load event of this control we can disable the autocomplete on the textbox. Let's test the above custom control on an ASPX page. Below is the code of ASPX page:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="HtmlForm" runat="server"> <MyControls:MyTextBox ID="MyTextBox" runat="server" DisableAutoComplete="true" ></MyControls:MyTextBox> </form> </body> </html>
You need to focus on DisableAutoComplete property of this custom control, if this is set to true the autocomplete on the textbox will be disabled.
The above ASPX page will be rendered as:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> </head> <body> <form name="HtmlForm" method="post" action="Demo.aspx" id="HtmlForm"> <div> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjE1ODQ2Mg9kFgICA" w9kfgicaq8pzbychgxhdxrvy29tcgxldgufa29mzmrktaexz xjfrwhscbgbtrl4ipu8mko="" /> </div> <input name="MyTextBox" type="text" id="MyTextBox" autocomplete="off" /> </form> </body> </html>
As you can see in above the autocomplete="off" will be rendered in output view source via the code set in the OnLoad of our custom control. That's it, we are done with disabling autocomplete on textbox. Do let me know your feedback, comments.
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18