C# List Control Utility
by Chad Finsterwald
Overview:
Binding to List Controls, finding the selected values, and checking and unchecking the items are some of the joys of asp.net development... And while I'd hate to deprive anyone of those simple pleasures, for those souls who find it a tedious chore I offer the List Control Utility. This library will streamline the following tasks:
Binding values to a List Control.
"Checking" or "Selecting" a set of items in a List Control.
Applying styles to an individual List Item.
Retrieving all "Checked" or "Selected" items to CSV or XML.
Putting on your pants --just seeing if your paying attention.
Methods
below is a list of the method names and descriptions in the List Control Utility. I did not give the signatures, but many of these have several overloads. You can view all the methods, their overloads, and documentation by clicking on the "View the Code" button below or by just downloading the .cs file.
DoListControl: Simplifies binding to a List Control. Can aslo be used to "pre-select" values in the List Control.
ApplyListItemStyles: Apply a CSS Style to the passed List Items values.
SelectByValue: Selects all List Items whose value matches the passed values.
SelectByText: Selects all List Items whose text matches the passed text.
SelectedItemsValueToCSV: Returns a comma seperated list of all the selected List Item values.
SelectedItemsTextToCSV: Returns a comma seperated list of all the selected List Item text.
SelectedItemsToXML: Returns a string XML fragment that contains the selected List Items value and text.
ClearAllSelectedItems: Unselects all selected List Items. C# String Library:
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Xml;
using System.Web.UI ;
using System.Web.UI.WebControls;
namespace CoreWebLibrary.Web.ControlUtilities
{
public static class ListControlHelper
{
public static void DoListControl(ListControl lc,
IList items)
{
DoListControl(lc, items, string.Empty, string.Empty, false);
}
public static void DoListControl(ListControl lc,
IList items, string textfield, string valuefield)
{
DoListControl(lc, items, textfield, valuefield, false);
}
public static void DoListControl(ListControl lc,
IList items, string textfield, string valuefield,
bool throwErrorOnNotFound, params string[] valuesToSelect)
{
DoListControl(lc, items, textfield, valuefield, FindListItemBy.ByValue, throwErrorOnNotFound);
}
public static void DoListControl(ListControl lc,
IList items, string textfield, string valuefield,
FindListItemBy selectedType, bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
lc.DataSource = items;
lc.DataTextField = textfield;
lc.DataValueField = valuefield;
lc.DataBind();
if (valuesToSelect.Length > 0)
ListControlHelper.Select(lc, throwErrorOnNotFound,
selectedType, valuesToSelect);
}
public static void DoListControl(ListControl lc,
IListSource items, string textfield, string valuefield)
{
DoListControl(lc, items, textfield, valuefield, false);
}
public static void DoListControl(ListControl lc,
IListSource items, string textfield, string valuefield,
bool throwErrorOnNotFound, params string[] valuesToSelect)
{
DoListControl(lc, items, textfield, valuefield, FindListItemBy.ByValue, throwErrorOnNotFound);
}
public static void DoListControl(ListControl lc,
IListSource items, string textfield, string valuefield,
FindListItemBy selectedType, bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
lc.DataSource = items;
lc.DataTextField = textfield;
lc.DataValueField = valuefield;
lc.DataBind();
if (valuesToSelect.Length > 0)
ListControlHelper.Select(lc, throwErrorOnNotFound,
selectedType, valuesToSelect);
}
public static void DoListControl(ListControl lc,
IDictionary items)
{
DoListControl(lc, items, "Value", "Key", FindListItemBy.ByValue,
false);
}
public static void DoListControl(ListControl lc,
IDictionary items, string textfield, string valuefield)
{
DoListControl(lc, items, textfield, valuefield, FindListItemBy.ByValue,
false);
}
public static void DoListControl(ListControl lc,
IDictionary items, string textfield, string valuefield,
bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
DoListControl(lc, items, textfield, valuefield, FindListItemBy.ByValue,
throwErrorOnNotFound, valuesToSelect);
}
public static void DoListControl(ListControl lc,
IDictionary items, string textfield, string valuefield,
FindListItemBy selectedType, bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
lc.DataSource = items;
lc.DataTextField = textfield;
lc.DataValueField = valuefield;
lc.DataBind();
if (valuesToSelect.Length > 0)
ListControlHelper.Select(lc, throwErrorOnNotFound,
selectedType, valuesToSelect);
}
public static void ApplyListItemStyles(ListControl lc,
IDictionary styles,
params string[] valuesToApplyTo)
{
foreach (string s in valuesToApplyTo)
{
ListItem item = lc.Items.FindByValue(s);
if (item != null)
{
CssStyleCollection css = item.Attributes.CssStyle ;
foreach (KeyValuePair style in styles)
{
css.Add(style.Key, style.Value);
}
}
}
}
public static void ApplyListItemStyles(ListControl lc,
IDictionary styles,
params ListItem[] itemsToApplyTo)
{
foreach (ListItem item in itemsToApplyTo)
{
CssStyleCollection css = item.Attributes.CssStyle;
foreach (KeyValuePair style in styles)
{
css.Add(style.Key, style.Value);
}
}
}
public static void SelectByValue(ListControl lc,
params string[] valuesToSelect)
{
ListControlHelper.Select(lc, false,
FindListItemBy.ByValue, valuesToSelect);
}
public static void SelectByValue(ListControl lc,
bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
ListControlHelper.Select(lc, throwErrorOnNotFound,
FindListItemBy.ByValue, valuesToSelect);
}
public static void SelectByText(ListControl lc,
params string[] valuesToSelect)
{
ListControlHelper.Select(lc, false,
FindListItemBy.ByText, valuesToSelect);
}
public static void SelectByText(ListControl lc,
bool throwErrorOnNotFound,
params string[] valuesToSelect)
{
ListControlHelper.Select(lc, throwErrorOnNotFound,
FindListItemBy.ByText, valuesToSelect);
}
public static string SelectedItemsValueToCSV(ListControl lc)
{
StringBuilder sb = new StringBuilder();
foreach (ListItem item in lc.Items)
{
if (item.Selected)
sb.AppendFormat("{0},", item.Value);
}
return sb.ToString().TrimEnd(',');
}
public static string SelectedItemsTextToCSV(ListControl lc)
{
StringBuilder sb = new StringBuilder();
foreach (ListItem item in lc.Items)
{
if (item.Selected)
sb.AppendFormat("{0},", item.Text);
}
return sb.ToString().TrimEnd(',');
}
public static string SelectedItemsToXML(ListControl lc, string nodeName)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<{0}>", nodeName);
foreach (ListItem item in lc.Items)
{
if (item.Selected)
{
sb.AppendFormat("",
item.Text, item.Value);
}
}
sb.AppendFormat("", nodeName);
return sb.ToString();
}
public static void ClearAllSelectedItems(ListControl lc)
{
if (lc is DropDownList)
{
if (lc.SelectedItem != null)
lc.SelectedItem.Selected = false;
}
else
{
foreach (ListItem item in lc.Items)
{
item.Selected = false;
}
}
}
#region Private Methods
private static void Select(ListControl lc,
bool throwErrorOnNotFound,
FindListItemBy findBy,
params string[] valuesToSelect)
{
foreach (string s in valuesToSelect)
{
ListItem item = ItemFindBy(lc, s, findBy);
if (item != null)
{
item.Selected = true;
}
else if (throwErrorOnNotFound)
{
throw new ApplicationException(string.Format("Value: {0} not found in ListControl {1}",
s, lc.ID));
}
}
}
private static ListItem ItemFindBy(ListControl lc,
string value,
FindListItemBy findBy)
{
if (findBy == FindListItemBy.ByText)
return lc.Items.FindByText(value);
if (findBy == FindListItemBy.ByValue)
return lc.Items.FindByValue(value);
return null;
}
#endregion
#region Public Enum
public enum FindListItemBy
{
ByValue,
ByText
}
#endregion
}
}
Use &;amp; Examples
below are a few examples of how to use the List Control Utility. It is a fairly straight forward collection of ListControl utilities so a few minutes of experimentation ought to suffice to learn how to use it.
Example One: DoListControl
this method will bind the passed items to the given ListControl and also allow you to pre-select certain items. It is a helpful syntax when programatically binding to ListControls from Collections or DataTables. public void SomeMethod()
{
//assumes there is a CheckBoxList on the aspx names cblNames
Dictionary<string, string> items = new Dictionary<string, string>();
items.Add("123", "Jack");
items.Add("456", "Jill");
items.Add("789", "Steve");
ListControlHelper.DoListControl(cblNames, items, "Value", "Key", false, "123");
}
would Yield the following results: JackJillSteve
Example Two: SelectByValue
the following will check (or select) the passed list values. public void SomeMethod()
{
//assumes there is a CheckBoxList on the aspx names cblDays like the one below.
ListControlHelper.SelectByValue(cblDays, "Mon", "Wed", "Fri");
}
would Yield the following results: MondayTuesdayWednesdayThursdayFriday
Example Three: SelectedItemsToXML &;amp; SelectedItemsValueToCSV
the two methods below help to retrieve selected List Items. (One easy way to persist values from a ListControl to a database is just to store them in a varchar as a comma-seperated string value. This also makes it easy to rebind the selected items to the ListControl by using SelectByValue method and simply passing in the CSV list in the params. Of course this is not for all situations, but can save time when you don't need to do anything with the values in the database.) public void SomeMethod()
{
//To convert the selected item in the "cblDays" CheckBoxList to
//XML and CSV you would use:
string xml = ListControlHelper.SelectedItemsToXML(cblDays, "Days");
string csv = ListControlHelper.SelectedItemsValueToCSV(cblDays);
}
the value of string
xml would be: <Days>
<item text="Monday" value="Mon" selected="true" />
<item text="Wednesday" value="Wed" selected="true" />
<item text="Friday" value="Fri" selected="true" />
</Days>
and the value of string
csv would be the less XML-citing, but still helpful: Mon,Wed,Fri
Example Four: ApplyListItemStyles
supposing you wanted to turn certain days bold and green, this could be accomplished by the code below. (When combined with the SelectedItemsValueToCSV, this can be an easy way to give users feedback on their choices.) public void SomeMethod()
{
//assumes there is a CheckBoxList on the aspx names cblDaysTwo like the one below.
Dictionary<HtmlTextWriterStyle, string> styles =
new Dictionary<HtmlTextWriterStyle,string>();
styles.Add(HtmlTextWriterStyle.FontWeight, "bold");
styles.Add(HtmlTextWriterStyle.Color, "Green");
ListControlHelper.ApplyListItemStyles(cblDaysTwo, styles, "Mon", "Wed", "Fri");
}
would Yield the following results: MondayTuesdayWednesdayThursdayFriday
Conclusion
happy binding! If you extend the library, please send me what you've done.
| 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。 |