Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

Disable Listbox in csharp asp.net

Modified: 2012/01/17 09:11 by m.wensveen - Categorized as: ASP.NET, Csharp
Currently we are building an application that stores user profiles and allows other people to view them, but not alter them.

Setting control property 'enabled' is 'false' to prevent editing works for a lot of asp webcontrols, but some are elusive. One of them is the asp:ListBox. I found a number of javascript/jquery/ajaxcontrol solutions, but wanted to keep my logic in one place.

One of the expected solutions would be: lb.Enabled = false; That does nothing, except setting a class="aspNetDisabled" which can be used for styling. Other things I tried included Disabling all ListItems in the ListBox. That resulted in a rendered 'select' without 'options'

Solution:
//(i'm looping through all the Controls in a asp:Panel, using reflexion to set properties)
// this example will focus on the ListBox part
foreach (Control cntrl in panel.Controls)
{
    Type typ = cntrl.GetType();
    if (typ.Name.Equals("ListBox"))
    {
        ListBox lb = (ListBox)cntrl;    
        if(lb != null)
        {
             lb.Enabled = false;
             lb.Attributes.Add("disabled", "disabled");
        }
    }
}
After that I needed to set the CSS so that the disabled but selected options would not have the same background color as their text color, plus I set the background color of the disabled select to the color other controls would get. That looks like this:
select:disabled
{
	background-color: #EBEBE4;
}

option:disabled
{
	color: #097799;
}
I hope this wil help someone.

 © Evident Interactive BV