Disable each item of Check box list

How can Disable each item of Check box list When perticular condition applied in code behind not in html or script

Sample code shows how to disable part of checkboxes. I have used repeater to create check boxlist because Microsoft's CheckBoxList (version 1.x)does not allow you to disable certain checkbox and keep others enabled, sample does not take care of other scenarios like maintaining view state of checkboxes or autopostback, but it should not be big task to add those functionality.

Run sample code

<%@ Page Language="C#"%>

<script runat="server">
        void Page_Load(object sender, EventArgs e){
            if(!IsPostBack){
                rptcheckboxes.DataSource = GetData();
                rptcheckboxes.DataBind();
            }
        }

        void Button1_Click(object sender, EventArgs e) {
            Response.Write("Selected CheckBox values are :"
+ Request.Params["MyCheckBoxList"]); } public ArrayList GetData(){ System.Collections.ArrayList data =
new System.Collections.ArrayList(); data.Add(new MyData("One","1",false,true)); data.Add(new MyData("Two","2",false,true)); data.Add(new MyData("Three","3",false,true)); data.Add(new MyData("Four","4",true,false)); data.Add(new MyData("Five","5",true,false)); data.Add(new MyData("Six","6",true,false)); return data; } publicclass MyData{ privatestring _Text; privatestring _Value; privatebool _Selected; privatebool _Enabled; publicstring Text{get{ return _Text;}} publicstring Value{get{ return _Value;}} publicbool Selected{get{ return _Selected;}} publicbool Enabled{get{ return _Enabled;}} public MyData(string text,stringvalue,
bool
selected,bool enabled){ _Text = text; _Value = value; _Selected = selected; _Enabled = enabled; } } string RenderSelected(bool selected){ if (selected){ return" checked=\"checked\" "; } return""; } string RenderEnabled(bool enabled){ if (!enabled){ return" disabled=\"disabled\" "; } return""; } </script> <html> <head> </head> <body> <form runat="server"> <asp:repeater runat="server" id="rptcheckboxes"> <itemtemplate> <input name="MyCheckBoxList" type="checkbox" <% # RenderSelected((bool)DataBinder.Eval(Container.DataItem,"Selected"))%> <% # RenderEnabled((bool)DataBinder.Eval(Container.DataItem,"Enabled"))%> value="<%#DataBinder.Eval(Container.DataItem,"Value")%>" /> <%#DataBinder.Eval(Container.DataItem,"Text")%> </itemtemplate> <separatortemplate> , </separatortemplate> </asp:repeater> <br /> <asp:Button onclick="Button1_Click" runat="server" Text="Button" /> <br /> Note: Disabled checkbox values are not posted. </form> </body> </html>
Bookmark with:
Technorati   Digg   Delicious   StumbleUpon   Facebook
My name is Jigar Desai I share my ideas on this site and you can contact me by filling contact form.

Categories