Code-less passing multiple selected items to a DataSource

Sometime on an ASPX page you need to use an item like a multiple select ListBox or a CheckBoxList but if this is to be a parameter to a DataSource, you find that there is no suitable property to pass as a parameter!

 

My solution is simple, just extend the control and add a new property that extracts the multiple values into a XML string. Why a Xml String? Simple, because it is robust for whatever happens to be in the Value for each item.

 

So we have this piece of simple code (using XmlTextWriter for performance)

 

namespace Ken.Web.UI.WebControls
{
    using System.Xml;
    using System.IO;
    public class CheckBoxLIst : System.Web.UI.WebControls.CheckBoxList
  
  public string CheckedValuesXml
  {
    get
    {
      using (var swriter = new StringWriter())
      {
        using (var xwriter = new XmlTextWriter(swriter) { Formatting = Formatting.Indented })
        {
          xwriter.WriteStartDocument();
          xwriter.WriteStartElement(ID);
          foreach (System.Web.UI.WebControls.ListItem item in this.Items)
          {
            if (item.Selected && !string.IsNullOrEmpty(item.Value))
            {
              xwriter.WriteElementString("item", item.Value);
            }
          }
          xwriter.WriteEndElement();
          xwriter.WriteEndDocument();
        }
        return swriter.ToString();
      }
    }
  }
}
  

I have to add my own control collections via web.config – so I would use:

<ken:CheckBoxList RepeatColumns="1" RepeatLayout="Flow" RepeatDirection="Vertical"
  runat="server" ID="AccountTransactionAccountsInput" 
  DataSourceID="AccountTransactionAccountsInputDb"
  DataTextField="text" DataValueField="value" />

And thus on my page I can have:

<asp:ObjectDataSource runat="server" ID="AccountTransactionResultGridDb" TypeName="Controller.Account"
  SelectMethod="GetFilteredTransactions">
  <SelectParameters>
    <asp:ControlParameter ControlID="AccountTransactionAccountholderInput" Name="accountHolder" PropertyName="SelectedValue" />
    <asp:ControlParameter ControlID="AccountTransactionAccountsInput" Name="accounts" PropertyName="CheckedValuesXml" />                
  </SelectParameters>
</asp:ObjectDataSource>

and avoid having any code behind to package the selected items. The same approach may be used for the ListBox.

Comments

Popular posts from this blog

Yet once more into the breech (of altered programming logic)

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

How to convert SVG data to a Png Image file Using InkScape