ASP.NET中设置CheckBox和RadioButton的默认值不可改变,并不丢失样式!

我们制作表单的时候都会用到多选CheckBox和单选RadioButton按钮。

有的时候我们希望它们的默认值不可以让用户改变。

最普遍的方法就是加上 enable=false。但这样就有了个问题,原本定义好的样式不见了!CheckBox变的很难看。

如何让CheckBox默认值不变,又不丢失原来的样式呢?

很简单,只要在每个CheckBox上添加属性onclick="this.checked=!this.checked;"

就是在用户改变了它之后再给改回去。

foreach (Control c in Page.Controls)
{
if (c.GetType().ToString() == "System.Web.UI.WebControls.CheckBoxList")
         
{
                         
foreach (ListItem l in ((CheckBoxList)c).Items)
                  
{
                                    l.Attributes.Add(
"onclick""this.checked=!this.checked");
                         }

                }

}

RadioButton就要复杂一点了!

foreach (Control c in Page.Controls)
                        
{
                            
if (c.GetType().ToString() == "System.Web.UI.WebControls.RadioButtonList")
                            
{
                                
//根据分析代码,我们看到单个的radio有唯一的id属性而且是这一个RadioButtonList控件的id+“_”+Index,所以第一步我们很容易找到这组radio被选中的radio的id
                                string radioId = ((RadioButtonList)c).ClientID +"_"+ ((RadioButtonList)c).SelectedIndex.ToString();
                                
foreach (ListItem l in ((RadioButtonList)c).Items)
                                
{
                                    
//添加onclick事件,在用户改变了默认值后,再恢复本组默认的选中值
                                    l.Attributes.Add("onclick","document.getElementById(""+radioId+"").checked=true");
                                }

                            }

                        }

 

 

posted @ 2008-01-12 18:23  寒 刚入门  阅读(2009)  评论(0编辑  收藏  举报
刚入门的寒