Monday, August 23, 2010

Create MaxLength on Textbox

Using the simple script below, multi-line textboxes will prevent a user from exceeding the MaxLength property.

* Note - using System.Text;

StringBuilder funcStr = new StringBuilder();
funcStr.Append("function isMaxLength(txtBox) {");
funcStr.Append("if(txtBox){");
funcStr.AppendFormat("return(txtBox.value.length <= {0});", aTextBox.MaxLength);
funcStr.Append("}}");

aTextBox.Attributes.Add("onkeypress", "return isMaxLength(this);");

ClientScript.RegisterClientScriptBlock(
   this.GetType(),
   "txtLength",
   funcStr.ToString() , true);

Monday, August 16, 2010

Using hidden field to track panels visibility

To track the javascript visibility changes of a panel in code behind, follow the description below.


Within the pages Form element add a hidden input field
<input type="hidden" name="panelStatus" id="panelStatus" value="">


Javascript that was set-up to handle the onclick event
function ShowHidePanel(img, id){
var panel = document.getElementById(id);
var status = document.getElementById("panelStatus");

if(panel != null){
  if(panel.style.display == ""){
    panel.style.display = "none"
    img.src = "/images/icn_plus.gif";
    status.value = "closed";
  }
  else{
    panel.style.display = "";
    img.src = "/images/icn_minus.gif";
    status.value = "open";
  }
}}


Grab current value in code behind and adjust panel accordingly
string status = Request.Form["panelStatus"];
ViewState["panelStatus"] = StringHelper.IsNullOrEmpty(status) ? ViewState["panelStatus"] : status;
if(ViewState["panelStatus"] != null && "open".Equals(ViewState["panelStatus"]))
  this.ShowHidePanel.Style.Add("display", "");
  this.ShowHideImg.ImageUrl="/images/icn_minus.gif";
}
else{
  this.ShowHidePanel.Style.Add("display", "none");
  this.ShowHideImg.ImageUrl="/images/icn_plus.gif";
}