Object Reference .NET

ref this.Object

ListBox Extension Method for Get and Set Selected Values

clock August 11, 2008 11:01 by author Magz
ASP.Net ListBox control allows two types of selection mode: single and multiple. Working in single selection mode is similar to working with DropDown list control. Use ListBox.SelectedValue to get the value that was selected by a user. In order to set a selection SelectedIndex property can be used or Selected property of a particular item should be set to true.

Example:
string selectedValue = MyListBox.SelectedValue; //get selected value
        
MyListBox.SelectedIndex = 0; //set the first item to  be selected
MyListBox.Items.FindByValue("val2").Selected = true; //select the item with value="val2"

However when using ListBox with SelectionMode="Multiple" ListBox.SelectedValue will return only the first selected item, not all of them. The code below shows how to create a simple extension method for a ListBox that will allow to get and set multiple selected items.

public static class ListBoxExtensions
{
    //return ArrayList of selected values
    public static ArrayList SelectedValues(this ListBox lbox)
    {
        ArrayList selectedValues = new ArrayList();
 
        int[] selectedIndeces = lbox.GetSelectedIndices();
        foreach (int i in selectedIndeces)
           selectedValues.Add(lbox.Items[i].Value);
        return selectedValues;
    }
    
    /// <summary>
    /// Select multiple items in a ListBox
    /// </summary>
    /// <param name="values">Values of the items that need to appear selected</param>
    public static void SelectedValues(this ListBox lbox, string[] values)
    {
        foreach (string value in values)
        {
            ListItem item = lbox.Items.FindByValue(value);
            if (item != null)
                item.Selected = true;
        }        
    }
}

Example:
<asp:ListBox ID="MyListBox" runat="server" SelectionMode="Multiple">
        <asp:ListItem Text="ItemText1" Value="val1"></asp:ListItem>
        <asp:ListItem Text="ItemText2" Value="val2"></asp:ListItem>
        <asp:ListItem Text="ItemText3" Value="val3"></asp:ListItem>
        <asp:ListItem Text="ItemText4" Value="val4"></asp:ListItem>
        <asp:ListItem Text="ItemText5" Value="val5"></asp:ListItem>
</asp:ListBox>    

List Box Example
To set items to be selected use

MyListBox.SelectedValues(new string[] {"val1", "val3"});

To get selected values call

ArrayList selectedValues = MyListBox.SelectedValues();

kick it on DotNetKicks.com


Get Checked Repeater Items Extension Method

clock June 16, 2008 17:24 by author Magz
Imagine you have a list of some items and checkboxes next to each item providing the ability for a user to make multiple choices and submit a result in one go. Weather you are implementing a news groups subscription, user survey or online products catalogue - the code behind is the same: we bind some object list to a data control like Repeater, add a checkbox to every item, set checkbox value to item ID.

Here is an example with list of books available for order

Repeater with checkboxes
<table>
    <asp:Repeater ID="rptBooks" runat="server"> 
        <ItemTemplate>
            <tr>     
                <td><input type="checkbox" runat="server" value='<%# Eval("BookID")%>' ID="chkBox" /></td>
                <td><%# Eval("Title")%></td>
                <td><%# Eval("Author")%> </td>
            </tr>
        </ItemTemplate>  
    </asp:Repeater>
</table>
<asp:Button ID="btnOrder" OnClick="btnOrder_Click" runat="server" Text="Order" />

When “Order” button is clicked we need get all selected book IDs (we store them in a value field of each checkbox). I suggest that we create an extension method that will do all the work and when we need to get selected items in any repeater in our code we will have to call only one method GetSelectedItems

public static class RepeaterExt
{
    /// <summary>
    /// Returns selected items array list in a repeater rpt
    /// </summary>
    /// <param name="chkBoxId">ID of a checkbox used in repeater to store the value of each item</param>
    public static ArrayList GetSelectedItems(this Repeater rpt, string chkBoxId)
    {
        var selectedValues = new ArrayList();
        for (int i = 0; i < rpt.Items.Count; i++)
        {
            var chkBox = rpt.Items[i].FindControl(chkBoxId) as HtmlInputCheckBox;
 
            if (chkBox != null && chkBox.Checked)
                selectedValues.Add(chkBox.Value);
        }
        return selectedValues;
    }
}

Now if we go back to our page with books catalog we can right the following:

protected void btnOrder_Click(object sender, EventArgs e)
{
using extenstion method to get checked items
selectedValues array will contain BookIDs that were ordered and you can store them in the database or process as required by your code.

Note that this example assumes that you need to use <input runat=”server”…  to be able to pre-polulate checked values or keep the state of the checkboxes after the postback. If none of this functionality is needed, the simplest way to get selected values is to use standard html

<input type="checkbox" value='<%# Eval("BookID")%>' name="chkBox" />

When the “Order” button is clicked Request["chkBox"] will return comma delimited list of selected BookIDs.

kick it on DotNetKicks.com


enum to friendly string extension method

clock June 3, 2008 12:05 by author Naz
We use enums quite extensively in our application as they are great for representing integral values in a strongly typed way using symbolic names eg.

if (Status == UserStatus.NotLoggedInAYear)
    ArchiveRecord();

is a lot more clearer and meaningful making it easier to maintain than

if (Status == 3)
    ArchiveRecord()

The enum names are not very friendly to the user and I recently read a some good articles creating user friendly strings for enum values and Enum description values which tried to solve this problem.

I think i've found a better solution to this problem using extension methods.

public enum RemovalType
{
    None,
    ManAndVan,
    FullRemoval,
    FullRemovalsAndPacking
}
 
public static class RemovalTypeEnum
{
    /// <summary>
    /// Returns a friendly enum name
    /// </summary>
    public static string ToFriendlyString(this RemovalType removalType)
    {
        switch (removalType)
        {
            case RemovalType.ManAndVan:
                return "Man & Van Service";
            case RemovalType.FullRemoval:
                return "Standerd removals service";
            case RemovalType.FullRemovalsAndPacking:
                return "Full removals and packing service";
            default:
                return removalType.ToString();
        }
    }
}

RemovalType removalType = RemovalType.ManAndVan;
removalType.ToFriendlyString()

This implementation creates an extension method on the actual enum "RemovalType" which then allows you to call a ToFriendlyString() on the instance of all enums of that type I think this a more fluid implementation and also means better performance compared to the other implementations as it doesn't need to use reflection.

You will notive i've decided to leave the default return value to call ToString() on the enum value which means you only need to implement the values that need to be made friendlier.

You can also call it easily inside databinded controls in the aspx page.

<%# ((RemovalType)Eval("ServiceType")).ToFriendlyString() %>


kick it on DotNetKicks.com



RecentComments

Comment RSS

Sign in