Object Reference .NET

ref this.Object

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 TryParse Extension Method

clock April 21, 2008 14:43 by author Magz
TryParse method is very helpful if you need to convert string representation of a value to a value itself. TryParse is better than Parse method because it doesn’t throw any exceptions and just returns a Boolean value to indicate weather the parsing was successful. Surprisingly there is no TryParse method available to use for Enum and this is where extension method can be extremely useful.

public static bool TryParse<T>(this Enum theEnum, string valueToParse, out T returnValue)
{
    returnValue = default(T);
    int intEnumValue;
    if (Int32.TryParse(valueToParse, out intEnumValue))
    {
        if (Enum.IsDefined(typeof(T), intEnumValue))
        {
            returnValue = (T)(object)intEnumValue;
            return true;
        }
    }
    return false;
}

Now it’s time to test our extension method! Here I have a simple UserType Enumeration
public enum UserType
{
    None = 0,
    Administrator = 1,
    Manager = 2,
    Consultant = 3
}

I want to parse QueryString parameter usertype and store the result in currentUserType variable.

currentUserType.TryParse(Request.QueryString["usertype"], out currentUserType);

if Request.QueryString["usertype"] is invalid UserType then currentUserType variable will be set to None (0).

kick it on DotNetKicks.com 



Search

Sign in