01 maggio, 2008

Extend ASP.NET ListBox

Hi, tonight we extend a standard ASP.NET control : the ListBox.
The ListBox have a property that allow you to specify a SelectedElement when the page is loading.. great ! . But if you have a Multiple ListBox, and you need to select many elements ?.
You can create a custom control that provide this function. You only have to set the DataSource and a list of selected item in comma separated value format.
Start with the demo code:

The new custom control derive from ListBox :
   1:  namespace MyControls
   2:  {
   3:      [DefaultProperty("Text")]
   4:      [ToolboxData("<{0}:CustomListBox runat=server></{0}:CustomListBox>")]
   5:      public class CustomListBox : ListBox
   6:      {


Now add property SelectedValues that you use to select item of the list box in comma separated values format.
   1:  private string _selectedvalues;
   2:   
   3:  [Bindable(true)]
   4:  [Category("Data")]
   5:  [DefaultValue("")]
   6:  [Localizable(true)]
   7:  public string SelectedValues
   8:  {
   9:      set
  10:      {
  11:          _selectedvalues = value;
  12:      }
  13:      get
  14:      {
  15:          return _selectedvalues;
  16:      }
  17:   
  18:  }


Now override the OnDataBound to selected the appropriate values on DataBound Event.

   1:  protected override void OnDataBound(EventArgs e)
   2:  {
   3:      base.OnDataBound(e);
   4:      if (_selectedvalues != null)
   5:      {
   6:          foreach (ListItem item in Items)
   7:          {
   8:              if (_selectedvalues.IndexOf(string.Format(",{0},", item.Value)) != -1)
   9:                  item.Selected = true;
  10:          }
  11:      }
  12:  }


And olso, you have to override this other two method to preserve data in postback events.

   1:  protected override void OnDataBinding(EventArgs e)
   2:  {
   3:      try
   4:      {
   5:          base.OnDataBinding(e);
   6:      }
   7:      catch (InvalidOperationException)
   8:      {
   9:          this.GetData().Select(DataSourceSelectArguments.Empty, new DataSourceViewSelectCallback(DoSelect));
  10:      }
  11:  }
  12:   
  13:  private void DoSelect(IEnumerable data)
  14:  {
  15:      this.PerformDataBinding(data);
  16:  }



Build your class, and add to your project.
Insert the control in your asp.net page :
   1:  <%@ Register Assembly="MyAssembly" Namespace="MyControls" TagPrefix="cc1" %>
   2:      <cc1:CustomListBox ID="CustomListBox1" runat="server" DataSource="MyDataSource" SelectedValues=",1,2,3,5"></cc1:CustomListBox>

Nessun commento:

Posta un commento