Introduction
The ASP.NET Framework comes with the CheckListBox
, a feature-rich ASP.NET server control to display list with checkboxes. Sometimes I need to change CSS of selected items.
To achieve that, I have decided to extend the CheckListBox
control and want to share so that it can be useful to me and others.
Using the Code
To achieve this, I have disabled the following properties:
RepeatDirection
RepeatLayout
RepeatColumns
public override RepeatDirection RepeatDirection
{
get
{
return RepeatDirection.Vertical;
}
}
public override RepeatLayout RepeatLayout
{
get
{
return RepeatLayout.Table;
}
}
public override int RepeatColumns
{
get
{
return 0;
}
}
Add a new property named "SelectedItemCSS
".
public string SelectedItemCSS
{
get
{
return ViewState["SelectedItemCSS"] != null ?
ViewState["SelectedItemCSS"].ToString() : String.Empty;
}
set
{
ViewState["SelectedItemCSS"] = value;
}
}
On Render
, put the control in a scrollable div
.
protected override void Render(HtmlTextWriter writer)
{
writer.Write("<div style='overflow-X:hidden;overflow-Y:auto;{0}'>",
(this.Width != null ? "width:" + this.Width.ToString() : String.Empty) +
(this.Height != null ? ";height:" + this.Height.ToString() : String.Empty));
this.Height = new Unit();
base.Render(writer);
writer.Write("</div>");
}
On Prerender
:
- Registered two method to change CSS of selected item
- Added client-side onclick event to all checkboxlist items
- Changed the CSS of selected items on every page load through JavaScript.
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (SelectedItemCSS == String.Empty)
return;
foreach (ListItem itm in this.Items)
{
itm.Attributes.Add("onclick",
"changeSelectedCss(this,'" + SelectedItemCSS + "');");
}
Page.ClientScript.RegisterClientScriptInclude("sortableJavaScript",
Page.ClientScript.GetWebResourceUrl(this.GetType(),
"ExtendedControls.js.ExtCheckListBox.js"));
Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID,
"<script>setSelectedCss('" + this.ID + "','" +
this.SelectedItemCSS + "');</script>");
}
The ExtendedControls.js has two methods for setting CSS of selected item.
function changeSelectedCss(Obj, selectedCss) {
if (Obj.checked == true) Obj.parentNode.className = selectedCss;
else Obj.parentNode.className = '';
}
function setSelectedCss(id, selectedCss) {
var theList = document.getElementById(id);
for (j = 0; j < theList.rows.length; j++) {
if (theList.rows[j].cells[0].children[0].checked == true)
theList.rows[j].cells[0].className = selectedCss;
else theList.rows[j].cells[0].className = '';
}
}
Sanjay K. Gupta is a Web/Software Developer Currently working with .Net Technologies. Although he knows VB language but, he mainly use C# language for programming. he is also interested in JavaScript and jQuery library. In his free time, he prefer to learn new technologies and write custom control libraries for ASP.NET.
In his 7+ years of software development career, he has worked on various technologies.