Tuesday, May 31, 2011

DropDownCheckBoxes: Using control

In this post I'll give more details about the DropDownCheckBoxes control.
After you've referenced the assembly and registered the control within application you may add its' markup to .aspx pages (see introduction post about how to add the control to the project).

From development point of view programming the control is no way different from using standard CheckBoxList control. It has same events (in fact only one is of interest - OnSelectedIndexChanged) and members (except those relevant to new rendering and client side behavior).

Example to start with

Let's have a look at an example and comment it. Bellow is a markup snippet from .aspx file:

...
<asp:DropDownCheckBoxes ID="yearsDropDownCheckBoxes" runat="server"
OnSelectedIndexChanged="checkBoxes_SelcetedIndexChanged"
AddJQueryReference="True" UseButtons="True" UseSelectAllNode="True">
<Style SelectBoxWidth="160" DropDownBoxBoxWidth="160" DropDownBoxBoxHeight="80" />
<Texts SelectBoxCaption="Year" />
</asp:DropDownCheckBoxes>
...
<div style="padding-top: 20px;">
<h1>
Selected items (updated whenever postback from any of the controls occurs)
</h1>
<asp:Panel ID="selectedItemsPanel" runat="server">
</asp:Panel>
</div>

Code snippet from the corresponding code-behind file:

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var years = new int[20];
var currentYear = DateTime.Now.Year;

for (int i = 0; i < years.Length; i++)
years[i] = currentYear--;

yearsDropDownCheckBoxes.DataSource = years;
yearsDropDownCheckBoxes.DataBind();
}
}

protected void checkBoxes_SelcetedIndexChanged(object sender, EventArgs e)
{
selectedItemsPanel.Controls.Clear();

foreach (ListItem item in (sender as ListControl).Items)
{
if (item.Selected)
selectedItemsPanel.Controls.Add(
new Literal()
{ Text = item.Text + " : " + item.Value + newLineConst } // HTML line break
);
}
}

The page contains a drop down check boxes for selecting years and a panel bellow which displays checked items whenever a postback from the control occurs (code for other controls from the picture was cut above):


From the example we see that a control yearsDropDownCheckBoxes is added to a page, the event handler checkBoxes_SelcetedIndexChanged for SelcetedIndexChanged event is assigned and the page load handler performs data binding for the control. Whenever a user clicks 'OK' button in the drop down list a postback goes to server and panel in the bottom of the page is filled with all checked items. Everything is straightforward and no different from using controls inherited from ListControl(including CheckBoxList).

Postback options & behavior

Properties DropDownCheckBoxes.AutoPostBack (default value is 'false') and DropDownCheckBoxes.UseButtons (default value is 'true') control the way postbacks from the control arise:

1. AutoPostBack == false && UseButtons == false - in this case no 'OK/Cancel' buttons are displayed in the bottom of the drop down box, no postback occurs when a user clicks outside control and drop down gets hidden. The server side event will be fired (if there's a handler specified) during postback from any other control from the page (in case selection change is detected). The behavior in this case is similar to other ASP.NET controls with AutoPostBack set to false;

2. AutoPostBack == true && UseButtons == false - no action buttons ( 'OK/Cancel' ) are displayed, postback occurs whenever a user leaves the expanded drop down by clicking outside it.

3. UseButtons == true (AutoPostBack value doesn't matter) - in this case there're action buttons displayed in the bottom of the drop down box. Postback is triggered only when a user clicks 'OK' button. Clicking 'Cancel' or outside the control collapses the drop down and restores the check box selection prior to opening the control.

JQuery dependency

JQuery library is delivered within the control assembly and the reference to it is automatically added to the page by the control. In case you have JQuery referenced on the page (e.g. in a master page) script errors may occur.

In order to turn off automatic reference adding set DropDownCheckBoxes.AddJQueryReference to 'false'.

Other control properties

  • DropDownCheckBoxes.UseSelectAllNode - if 'true' then there's a 'Select all' check box added on top of other check boxes in the drop down. Clicking the check box changes all other check boxes' to corresponding state.
  • DropDownCheckBoxes.Texts - a complex property that allow to change default texts of the control elements (caption, button names, 'Select all' check box), e.g. for localization.
  • DropDownCheckBoxes.CssClass - specifies CSS class name applied to the control (specifically the DIV element which wraps all the contents). Setting this peoperty has the same effect as using DropDownCheckBoxes.Style.SelectBoxCssClass property.
  • DropDownCheckBoxes.Style - a complex property that allows applying CSS classes to the control and also directly specify sizes of the control elements (height of the select box, width and height of drop down box).

NOTE: The control can work within update panel without any adjustments.

The project page at Codeplex can be found here.

110 comments:

  1. hi there. i got a problem using this control.

    as soon as i add the

    Style DropDownBoxBoxWidth="100"

    part in the control's html


    i get a parser error with the error message "Ambigious match found"

    i have no clue how this happens but it even happened when i started a clean web application.

    im using .NET 3.5

    ReplyDelete
    Replies
    1. I dont know if you sorted it out or not.. but i figured this can be solved by using code behind:

      dropdownbox.DropDownBoxBoxWidth=100

      Delete
    2. Please use <Style2 DropDownBoxBoxHeight="130" DropDownBoxBoxWidth="200" in your Code.

      Gopal chauhan

      Delete
  2. I've got this issue on codeplex, thanks for highlighting it. I'll have a look at it as soon as I've time.

    ReplyDelete
  3. How do you clear the checked items in code behind?

    ReplyDelete
  4. How do you clear the selected items in code behind?

    ReplyDelete
  5. foreach (ListItem item in dropdown.Items)
    {
    if (item.Selected)
    {
    item.Selected = false;
    }
    }

    ReplyDelete
  6. That's what I thought. However I am using the control in an update panel and when I try to clear the selected items in code behind the checks remain. If I remove the update panel and run it the selected items get cleared. Any ideas?

    ReplyDelete
  7. did you insert in runat="server" as an attibute on the updatepanel?

    ReplyDelete
  8. Yes. I have several standard dropdownlists in the update panel that are working fine. We needed yours for the multiselect capability.

    ReplyDelete
  9. i didnt write the control,but do you mind posting the html of your page?

    ReplyDelete
  10. I have also tried clearing all the items from the list and rebinding it and I still get the same items selected. Could it be a view state problem?

    ReplyDelete
  11. are you using a objectdatasource to fill the dropdown?

    ReplyDelete
  12. disable the sqldatasource (dont set the DataSourceID of the dropdown) and then try clearing the dropdown's items,(i might be wrong but) the sqldatasource refreshes the dropdowns items (checking them again) after a each postback is done
    i think that is whats screwing up your code

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. There was a bug in the control which was resetting the server side selection replacing it with client side selection before the post back (when the control is within UpdatePanel).

    There's a new release at the CodePlex project page with the bug fixed:
    http://dropdowncheckboxes.codeplex.com/

    ReplyDelete
  15. I need, when user select multiple values, change the property SelectBoxCaption, but not on the server. I need do it on client(without postback). How can i do it.

    ReplyDelete
    Replies
    1. hi, i am also suffering with same issue. if you have the solution for this issue can you please tell me how can i do this thank you.

      Delete
  16. Could you post a 2.0 framework version on CodePlex please?

    ReplyDelete
  17. Dear, First of all thanks, this is the only control so far working properly inside a gridview, which is wonderful, without any issues. Anyways, i have another request, is it possible to extent this control and add a textbox against each checkboxlist item, i have a complex scenario where the user will select each Item and against that item he has to give a value, so can you please help me or explain me, how to extent this model to include a textbox, either using server side control like textbox or client side using Jquery or javascript. I hope to hear back soon from you.
    Rahman

    ReplyDelete
  18. can we apply validation on this control? required field something like that? it is giving me error.


    thanks
    Kamran

    ReplyDelete
  19. Great control man. Working find on mine.

    There something bugging me.

    For the first times when postback occur why it calling ...selectedIndexChanged(...) function twice. So i get the output repeated twice. But it working find after that. Anyone got the same?

    Thank You

    ReplyDelete
    Replies
    1. Hi,
      I got the same issue, can you please tell the solution

      Delete
  20. Thanks for this great control.Good job...
    I have problem when i want to use your control in a page in which there is a reference to latest jquery.I tried to disable AddJQueryReference=false ,and put references into my page,but error still occurs (jQuery is undefined).

    ReplyDelete
  21. i am getting the Following Error while using this ..

    'System.Web.UI.HtmlControls.HtmlGenericControl' does not contain a definition for 'DataSource' and no extension method 'DataSource' accepting a first argument of type 'System.Web.UI.HtmlControls.HtmlGenericControl' could be found (are you missing a using directive or an assembly reference?)

    This means that it doesnot have property of DataSource ??? Any Ideas PLease!!

    ReplyDelete
  22. I am using this control, the postback occurs twice on the onSelectionIndexChanged() event.can some one help me how to fix this issue.

    ReplyDelete
  23. Thank you ... issue got resolved... anyway i have another query which is... How can you show the selected values at the caption !!

    ReplyDelete
    Replies
    1. hi, i am also suffering with same issue. if you have the solution for this issue can you please provide me how can i do this thank you.

      Delete
  24. Hi,

    Please paste the following code in DropDownScript.js file and make Autopostback= false for the dropdown.

    Then call the below function inside the checkBoxClickHandler.


    DropDownScript.prototype.updateText = function () {
    var text = '';
    $( "#" + this.id + " input:checked" ).each( function()
    {
    if (text == '')
    text = $(this).next('label').text() ;
    else
    text = text + ', ' + $(this).next('label').text() ;
    });
    if(text == '')
    $("#" + this.selId).find($("div[id^='caption']")).html('Select');
    else
    $("#" + this.selId).find($("div[id^='caption']")).html(text);
    }

    ReplyDelete
  25. Can you please tell me how to do a validation by using ExtendedRequiredFieldValidator.

    ReplyDelete
  26. Is there a way to only do a post back when selections have changed? Right now a post back occurs when you leave and click outside the drop down (as described above in AutoPostBack == true && UseButtons == false section). But, it would be nice to have it only post back when a change was made.

    Thanks in advance.

    ReplyDelete
  27. I have array with more options

    I have used:

    if (lbl_id_dias.Text != "" && lbl_id_dias.Text != "0")
    {
    string cad_idDias = lbl_id_dias.Text;
    string[] arr_idDias = cad_idDias.Split(',');
    for (int i = 0; i < arr_idDias.Length; i++)
    {
    ddl_Dia.SelectedValue = ddl_Dia.Items.FindByValue(arr_idDias[i]).Value;
    }
    }
    UpdatePanel_filtros.Update();

    -----
    Only check last option of array.

    Please how do for check all options of the array?

    neonemesis15@gmail.com

    ReplyDelete
  28. I get the error

    "Microsoft JScript runtime error: 'DropDownScript' is undefined"

    When trying to load the control in my web page. My web page is using AJAX with Teleriks Rad Controls. When I use your sample web page project the control is working fine. I have tried to set the AddJQueryReference to "False" but it makes no difference.

    ReplyDelete
  29. Hi,

    I am trying to use this tool with the Gridview control. The challange that i am facing now is how do we bind this control with the data while we are in edit mode on Gridview.

    Can anyone route the right way??

    -R

    ReplyDelete
  30. Can we validate this control??If yes then How?

    ReplyDelete
  31. I have problem, that Dropdowncheckbox doesn't bind, selectboxcaption is outside of DropDownCheckbox and is not active on click. I have no ide what is wrong. Can anybody help me?

    ReplyDelete
  32. Hi I am really digging this control and started liking this. One of the challange that im facing right now is how can we trigger a java script function on checkbox click so that we can change the text of the Control from "Select" to "Selected" so that end user can be sure that s/he had selected the options within the control. So far, the text does not change.

    ReplyDelete
  33. I have a problem, that use tab index of dropdownchecbox. I can't focus into dropdowncheckbox when press TAB in asp.net

    ReplyDelete
  34. Hi, For each each control event triggered postback is getting done. How to avoid postback

    ReplyDelete
  35. issues adding the control in the child page in asp.net it keep showing the following error.
    Microsoft JScript runtime error: 'Sys.WebForms.PageRequestManager' is null or not an object

    ReplyDelete
  36. I have a menu control in my master page which is creating a init_error for the dropdown and not working properly. If i comment out the code for menu then it works fine. Can you help me?

    ReplyDelete
  37. This comment has been removed by the author.

    ReplyDelete
  38. This comment has been removed by the author.

    ReplyDelete
  39. I am getting an error in IE8 for long running JScript. I am loading this box with almost 50000 selection list.This works fine with chrome but IE8 hangs.

    ReplyDelete
  40. Nice Control...Working Fine...

    ReplyDelete
  41. This control is not working in content page, please do u have idea . please ans me, why it is not working in content page ????

    ReplyDelete
  42. how do you filter multiple selections in jquery?

    ReplyDelete
  43. How do I show the selectboxcaption as ToolTip when mouse select the control? How do I select all checkboxlist at default?

    Thank you

    ReplyDelete
  44. Hey All, I want to check all in the dropdown..do we have any shortcut to do it...I have thousands items in the dropdown...looping is making my page slow...how to automatically make it selected?

    foreach (ListItem item in DD.Items)
    {
    item.Selected = true;
    }

    ReplyDelete
  45. I have added control on my page , but the control is not visible .. please help

    ReplyDelete
  46. Hi,
    This is Munir, I want to use this control with "JQuery accordion UI " but its creating a problem.

    Accordion tabs disappeared.
    with out this control, they work fine.
    Any body help me.

    ReplyDelete
  47. Hi,
    I'm on the stage of learning asp.net and using this control in my project.
    One thing i didn't understand, when i use this control without it works fine and gives proper result. But when i'm using an Update Panel control, it stops responding and only shows the caption, not even the outline of the dropdownlist is shown.
    if any one can help me understand what the issue is or where am I going wrong?
    Thank you.

    ReplyDelete
  48. Hi,

    Very nice control.

    How can I add a Textbox to the right of the checkbox when the user checked?

    Thanks.

    ReplyDelete
  49. I am using this control, the postback occurs twice on the onSelectionIndexChanged() event.can some one help me how to fix this issue.

    ReplyDelete
  50. The control throwing 'DropDownScript is undefined' exception when trying to place it inside gridView. Please suggest, thanks

    ReplyDelete
  51. Have an issue with the control when used in an UpdatePanel. If the control is initially set to Visible=false, if you update it to Visible=True in an UpdatePanel, only the word Select is rendered.

    ReplyDelete
  52. The control throwing 'DropDownScript is undefined' exception when trying to place it inside gridView. Please suggest, thanks

    ReplyDelete
  53. I get the error

    "Microsoft JScript runtime error: 'DropDownScript' is undefined"

    When trying to load the control in my web page. My web page is using AJAX/Update panel. When I use your sample web page project the control is working fine. I have tried to set the AddJQueryReference to "False" but it makes no difference.

    ReplyDelete
  54. Microsoft JScript runtime error: 'DropDownScript' is undefined

    I'm getting the above mentioned issue while using this control in the GridView.
    Kindly help.

    ReplyDelete
    Replies
    1. Make sure that the "Build Action" (in properties) for the embedded resources is set to be "Embedded Resource", and also check the namespace values for all of the projects that are referenced are good, i.e. in the assembly properties and in the constants used in the dropdown class....

      Delete
  55. How to set the value for the drop down items? At the moment the item.value is equal to item.text

    ReplyDelete
  56. This comment has been removed by the author.

    ReplyDelete
  57. Gridview Filter using saplin not working..

    Find the refrence below in asp.net forum

    http://forums.asp.net/t/1901660.aspx/1?Dropdown+value+get+empty+after+selected+index+changed

    ReplyDelete
  58. how can i load data from database?

    ReplyDelete
  59. Hi,

    I am trying to add this control to Grid view and want to display value of check box selected on to a label.I am unable to achieve this. Can you please help me with this.

    ReplyDelete
  60. Not working in VS2012 version.

    How can we do it using .net 4.5

    ReplyDelete
  61. Thanks for controls
    its very good.
    but tell me
    how to bind this control using json and ajax ?
    please reply its urgent

    ReplyDelete
    Replies
    1. Hey Viral,
      Were you able to find out how you can bind the control using json and ajax. I am trying to implement the selectedindexchanged using json and ajax and wanted to know how I can do using ajax and json. Can you or anybody please let me know?
      Thanks.

      Delete
  62. I'm trying to pass the entire selection to report parameter that accept multi-values within asp.net vs2010 application. Can someone inform me how can be done using this dropdowncheckbox control?

    ReplyDelete
  63. Thanks for the article
    I want to change the color of SelectBoxCaption
    Is it possible to do that?

    ReplyDelete
  64. Hi,Once the design specifications have been decided for Web Design Cochin, it is best to start planning the navigation structure and content of the Web pages.Once the mockup is finalized the graphics are created and the coding of the Web page can be done using a mark up language such as hypertext markup language, or HTML. Thanks......

    ReplyDelete
  65. I am using the control in my project and it works well when the asp page is shown in IE9 and Chrome, but when it is shown in Firefox the control doesn't display, in the browser only shows a caption with a text.

    Can any one tell me how can I solve this?

    ReplyDelete
  66. It is very nice control to use
    but its not working on MasterPage
    can you plz tell me how to use it on master Page

    ReplyDelete
  67. How to make this control opaque?for eg when I have two controls one below the other it showing the other control within the control.

    Thanks,

    Gokul

    ReplyDelete
  68. This comment has been removed by the author.

    ReplyDelete
  69. HI ,
    The MultiSelect Control Developed is very good i have used in my project,
    The issue am facing is that the control overlaps the other control and i have adjusted the css as well but all my efforts are in vain..
    could you please help me out

    ReplyDelete
  70. Dear All,

    The current version of the control is built for .NET 3.5 but my web pages is .NET 2.0 .Could you help me on how implement this control in .NET 2.0?

    Please help me

    ReplyDelete
  71. how to increase height of selectboxcaption (selectboxheight) ?

    ReplyDelete
  72. Can we have only one button as OK , instead of both OK and Cancel as it is creating confusion for users even if they click outside of drop down it is applying the selection.(Cancel is working as OK !!).

    your help is appreciated.

    Thank you
    nandish

    ReplyDelete
  73. I'm using this control for several fields on my form. Some are loaded with data on the initial page load, and others on a partial PostBack when a GridView item is clicked. This is a must as the values in the control change based on the record being edited. The controls loaded on the initial page load post selected values as expected. The instances that are loaded on a partial page PostBack always indicate no items are selected. I am able to programmatically select the items associated with the editing record after binding to a DataTable stored in ViewState, but I can't get the values when updating the record. All controls are in UpdatePanels so I know that isn't the issue.

    I think I've run into this issue with other controls and resorted to using hidden fields populated client side before posting back. However, I haven't been able to get the values for this control on the client. It appears values aren't even being stored even though I bind to a DataValueField. I can't use the innerText due to the complexity of mapping to an id. How can I get the values client side?

    ReplyDelete
    Replies
    1. DropDownScript.prototype.doPostBack = function () {
      var items = this.getItems();
      if (items.length > 0) {
      if (this.postbackFunction)
      this.postbackFunction.call();
      };
      };

      Delete
  74. Thankx Dear for this usefull control.


    Gopal chauhan

    ReplyDelete
  75. please how to use it inside a gridVIEW IN ASP.NET C# ,??

    ReplyDelete
  76. Hi

    I want ask about DropDownCheckBoxes, i use it with master pages. in my page i use one server tag, i put it in master page so in other web form i didn't use runat server in form. when i use DropDownCheckBoxes, it didn't work ? why ?

    ReplyDelete
  77. how to validate this control

    ReplyDelete
  78. how to validate this control

    ReplyDelete
  79. Validate this control with the <asp:ExtendedRequiredFieldValidator - it works exactly the same as the RequiredFieldValidator - if it's not in your toolbox, just type it in - I had to set the ControlToValidate parameter manually to. After that, it worked just fine

    ReplyDelete
  80. onselectindexchanged i got twice execution plz solve this issue..

    ReplyDelete
  81. I am using ASP.NET in Visual Studio 2010 with .NET 4.0, so I don't know if this works for other things. In regards to the issue of it firing twice I basically remove the event handler after it's use. So what I have essentially is...


    protected void myDropDownCheckBoxes_SelectedIndexChanged(object sender, EventArgs e)
    {
    myDropDownCheckBoxes.SelectedIndexChanged -= new System.EventHandler(this.myDropDownCheckBoxes_SelectedIndexChanged);
    //Do other stuff, for me it's looking at the itemcollection and checking which items are "selected"
    }

    Why? Just from googling, not my investigate discoveries, the DropDownCheckBoxes control contains two children controls, a dropdownlist control and checkbox controls. Each of these is apparently responsible for firing off the event, hence why there are two. Again, these are other people on the internet saying this and I am still a novice in regards to how ASP.NET does a lot of stuff under the hood.

    ReplyDelete
  82. Does not work on ASP .Net content pages, seems the problem is caused by masterpage. Why?

    ReplyDelete
  83. Found it: one must put a scriptmanger inside the form tag of the masterpage!

    ReplyDelete
  84. Having a conflict with Datepicker in jquery. when dropdowncheckbox is AddJQueryReference="true" the datepicker is not working in the textboxk. but if you turn it to "false" the datepicker works in textbox but the problem with the dropdowncheckbox now is that the select all is not working. it will only work 1 time but next select all doesnt work anymore.. HELP Please.

    ReplyDelete
    Replies
    1. Hey,

      Even i have the same issue. did anyone provide you the solution.
      If do so please provide me the solution for the issue that you have faced.
      Thanks
      Shiv

      Delete
  85. It is not working if web page has master page in this case how to use it

    ReplyDelete
  86. Hi,
    Could you please explain me how to adjust the height of the Dropdown its taking default 16 Px only.
    Thanks

    ReplyDelete
  87. This comment has been removed by the author.

    ReplyDelete
  88. Is It possible to display the selected items in dropdown checkbox control in text caption area. Can anyone please tell me hoe to do this.
    Thank you

    ReplyDelete
  89. How can I show the selected values at the caption !! can anyone provide solution for this issue please give me

    ReplyDelete
  90. Hi , I am trying to use this in VS 2015, but JQuery error occurs when I click on DropDown icon to see items.
    .hitch("click", this.documentClickHandler, this); is not a function

    ReplyDelete
  91. hi, can we use this code for page which is interlinked with master page. i am getting issue in master page when i use that above code in child page.

    ReplyDelete