Friday, April 27, 2012

Disable DropDownList without blur effect in Asp.Net

In View mode, we will set the .Enabled property of controls false, to prevent the users from modifying the values in the control, but this will create a blur effect on the controls and the text in the controls will not be visible clearly.  Especially in the DropDownList control, when the control is disabled the user will not be able to see the other options available in the DropDownList control.

We can overcome this with the help of some JavaScript, adding this script will enable the users to view the other options in the dropdown, but still makes sure that the user cannot change the currently selected option in the View mode.


To see on how to achieve the same effect using jQuery refer the post Asp.Net jQuery Restrict dropdown list Selection without disabling. 

Here is the script which we will be using to create the disable effect, add this script between the <head><<head> tags.

<script type="text/javascript" language="javascript">
function getQuerystring(key, defaultVal)
{
  if (defaultVal == null)
  {
      defaultVal = "";
  }
  key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if (qs == null)
  {
      return defaultVal;
  }
  else
  {
      return qs[1];
  }
}
//
function setDefaultIndex(control)
{
  if (getQuerystring("mode", null) == "view")
  {
      control.defaultIndex = control.selectedIndex;
  }
}
//
function setSelectedIndex(control)
{
  if (getQuerystring("mode", null) == "view")
  {
      control.selectedIndex = control.defaultIndex;
  }
}
</script>

The getQuerystring() function is used to extract the values passed in the QueryString of the page, here we assume that for View mode, a parameter mode=view is passed with the query string of the page request.

Once the script is in place, we can call the javascript functions in the onfocus and onchange events get the disable effect.

<
asp:DropDownList
ID="drpNames"
runat="server"
onfocus="javascript:setDefaultIndex(this);" onchange="javascript:setSelectedIndex(this);">
</asp:DropDownList>

Now in the View mode the, DropDownList will appear as though it is enabled but the user will not be able to make any changes to the selected item in the DropDownList, doing so will reset back to the original item which was selected when the page was loaded.

Thus we have disabled the DropDownList control, without the blur effect.


There's a much simpler approach of achieving this effect using jQuery, to see on how to achieve the same effect using jQuery refer the post Asp.Net jQuery Restrict dropdown list Selection without disabling 

Search Flipkart Products:
Flipkart.com

1 comment:

Anonymous said...

very nice helpful tip