Is it checked or not quite? Multi-state checkboxes are in the menu today. Which, of course, begs the question “Doesn’t the WebDataGrid already support checkbox columns out-of-the box?”. Why yes, it does support a tri-state CheckBox Field, but there are cases where you might need a little bit more flexibility. As we have been reminded on our Product Ideas feedback platform, having more checkbox states with enabled and disabled variations is something the users themselves can benefit directly. This is partly because the Grid’s editing behavior treats checkboxes fields in bulk (as in the entire column) and perhaps even because there’s no visual cue the checkboxes in the column are not editable. So if you want more than the standard tri-state checkboxes that can be setup for each row – read on. Based on the feedback we received, the team has prepared a solution and I added my own spin as well and I want to share those with you.
Setup
There are a few things assumed here – you want to show a data grid with checkbox column bound or unbound, but you also want to use the Editing behavior and to control if each row’s checkbox is editable based on a condition or your other data columns. This way from three states, in combination with enabled and disabled, we go to six and that’s something you might need to store in more than one column. Depending on your data and case that extra column can be used as a flag weather or not the checkbox should be active or the entire state. Implementation of something like this can be very different, so a bit of adapting might be required but I’ll try to point out the basics that are reusable and mark optional features in the demo code.
Basics
The idea behind adding a disabled state is quite clever – replace the checkbox image with respective inactive image and perform runtime check for those images to prevent editing. This way you get control over the visual indication, but also on the image details you can use for detection. So you need 3 images, along with a settings object for the client-side with paths and values for them and mapping between checkbox and their hidden state cells.
Client events to handle:
- Initialize– go through checkboxes that have extra state and apply enabled/disabled look
- Handle Editing’s CellValueChanging to prevent disabled editing. Also keep in mind the event is fired when using the API so if you want to still be able to change values programmatically client-side you might need to use the “_set_value_internal” method instead.
- If you are using unbound checkboxes with a header box, you should also handle the HeaderCheckBoxClicked to set proper state and perhaps value.
You can use either bound fields from your current data, add new ones to do that if not available, use unbound fields with the sole purpose of holding flags or even enable and disable checkboxes based on logic executed on the client.
External flag approach
This uses the standard checkbox functionality along with applying editable states based on a flag – that can either be another data column, predetermined by server logic and carried over as (un)bound field or completely based on client side logic. The implementation is really up to you, I will use another bool column as part of the data – and since I have two checkbox columns the last two fields carry disabled flags for them:
- <ig:WebDataGridID="WebDataGrid1"runat="server"Height="350px"Width="100%"AutoGenerateColumns="False"DataKeyFields="ID"StyleSetName="IG">
- <Columns>
- <ig:BoundDataFieldDataFieldName="ID"Key="ID">
- <HeaderText="ID"/>
- </ig:BoundDataField>
- <ig:BoundDataFieldDataFieldName="CheckBoxState"Key="CheckBoxState">
- <HeaderText="CheckBox State"/>
- </ig:BoundDataField>
- <ig:BoundCheckBoxFieldDataFieldName="BoundCheckBox"Key="BoundCheckBox"DataType="System.Boolean">
- <HeaderText="Bound CheckBox"/>
- </ig:BoundCheckBoxField>
- <ig:BoundCheckBoxFieldKey="DisableBoundCheckBox">
- <HeaderText="Check to disable corresponding BoundCheckBox"/>
- </ig:BoundCheckBoxField>
- <ig:UnboundCheckBoxFieldKey="UnboundCheckBox"HeaderCheckBoxMode="TriState">
- <HeaderText="UnboundCheckBox"/>
- </ig:UnboundCheckBoxField>
- <ig:UnboundCheckBoxFieldKey="DisableUnboundCheckBox"HeaderCheckBoxMode="TriState">
- <HeaderText="Check to disable corresponding UnboundCheckBox"/>
- </ig:UnboundCheckBoxField>
- <%-- Hidden columns to store the states for the CheckBoxFields --%>
- <ig:BoundDataFieldKey="BoundCheckBoxDisabled"Hidden="true"DataType="System.Boolean">
- <HeaderText="Bound CheckBox Disabled?"/>
- </ig:BoundDataField>
- <ig:BoundDataFieldKey="UnboundCheckBoxDisabled"Hidden="true"DataType="System.Boolean">
- <HeaderText="Unbound CheckBox Disabled?"/>
- </ig:BoundDataField>
- </Columns>
- <ClientEventsInitialize="WebDataGrid_Grid_Initialize"HeaderCheckBoxClicked="WebDataGrid_Grid_HeaderCheckboxClicked"/>
- <Behaviors>
- <ig:EditingCore>
- <EditingClientEventsCellValueChanging="WebDataGrid_Editing_CellValueChanging"CellValueChanged="WebDataGrid_Editing_CellValueChanged"/>
- <Behaviors>
- <ig:CellEditing>
- <ColumnSettings>
- <ig:EditingColumnSettingColumnKey="ID"ReadOnly="True"/>
- </ColumnSettings>
- <EditModeActionsMouseClick="Single"EnableOnKeyPress="true"/>
- </ig:CellEditing>
- </Behaviors>
- </ig:EditingCore>
- </Behaviors>
- </ig:WebDataGrid>
Initial state based on the values of those is established and the disabled checkbox images replace the defaults where needed:
- var styleName = "<%=this.WebDataGrid1.StyleSetName %>" || "Default";
- var clientSettings = {
- "true": { src: "images/" + styleName + "/ig_checkbox_disabled_on.gif", value: true, chkState: 1 },
- "false": {src: "images/" + styleName + "/ig_checkbox_disabled_off.gif", value: false, chkState: 0 },
- "null": { src: "images/" + styleName + "/ig_checkbox_disabled_partial.gif", value: null, chkState: 2 },
- "columns": {2: 6, 4: 7}
- };
- function WebDataGrid_Grid_Initialize(sender, eventArgs) {
- // Set initial enabled / disabled state for all checkboxes
- try {
- var rows = sender.get_rows();
- var rowCount = rows.get_length();
- for (var i = 0; i < rowCount; i++) {
- var row = rows.get_row(i);
- for (columnIndex in clientSettings["columns"]){
- // Set the correct enabled/disabled states:
- var checkBoxCell = row.get_cell(columnIndex);
- var hiddenStateCell = row.get_cell(clientSettings["columns"][columnIndex]);
- var isDisabled = hiddenStateCell.get_value();
- SetCheckState(checkBoxCell, isDisabled, hiddenStateCell);
- }
- }
- }
- catch (ex) { }
- }
- function SetCheckState(cell, isDisabled, checkStateCell) {
- // Set Enabled or disabled state to a cell (adjust image and title/alt) and store in secondary cell.
- try {
- if (isDisabled === isCellDisabled(cell)) return;
- var checkBoxElem = cell.get_element().getElementsByTagName("img").item(0); //get checkbox image
- var chkStates = clientSettings[String(cell.get_value())]; //get state info
- if (!chkStates) return;
- if (isDisabled === true) {
- // Set the disabled values of src and title for the checkbox
- checkBoxElem.src = chkStates.src;
- checkBoxElem.title = "Disabled " + checkBoxElem.title;
- checkBoxElem.alt = "Disabled " + checkBoxElem.alt;
- }
- else {
- // re-set value to restore state
- checkBoxElem.src = "";
- //use _internal to force setting the same value
- cell._set_value_internal(chkStates.value, chkStates.chkState);
- }
- checkStateCell.set_value(isDisabled); // Store the new checkbox state value in the corresponding hidden checkbox
- }
- catch (ex) { }
- }
- function isCellDisabled(cell) {
- var checkBoxElem = cell.get_element().getElementsByTagName("img").item(0);
- return checkBoxElem && checkBoxElem.src.toLowerCase().indexOf("disabled") >= 0;
- }
Prevent edits on disabled checkboxes and for unbound fields preserve the state when the header box is used:
- function WebDataGrid_Editing_CellValueChanging(sender, eventArgs) {
- // Prevent edit actions on disabled checkboxes
- try {
- var currCell = eventArgs.get_cell();
- if (isCellDisabled(currCell))
- eventArgs.set_cancel(true); // cancel event to prevent value change
- }
- catch (ex) { }
- }
- function WebDataGrid_Grid_HeaderCheckboxClicked(sender, eventArgs) {
- var columnIndex = eventArgs.get_column().get_index();
- var rows = sender.get_rows();
- var rowCount = rows.get_length();
- // When the header of the "UnboundCheckBox" column is clicked,
- // set the check states for all while maintaining enabled/disabled states
- if (clientSettings["columns"][columnIndex]) {
- for (var i = 0; i < rowCount; i++) {
- var row = rows.get_row(i);
- var unboundCheckBoxCell = row.get_cell(columnIndex);
- var hiddenUnboundCheckBoxCell = unboundCheckBoxCell.get_row().get_cell(clientSettings["columns"][columnIndex]);
- var unboundCheckBoxCellVal = hiddenUnboundCheckBoxCell.get_value();
- SetCheckState(unboundCheckBoxCell, unboundCheckBoxCellVal, hiddenUnboundCheckBoxCell);
- }
- }
- }
Of course, keeping state for unbound fields is just as optional as the header box itself – it’s a matter of what you might need. At this point you can use the SetCheckState function to toggle state and you can provide the user with various ways of doing that if needed (see demo code handling value changes of neighboring standard checkbox fields).
P.S. If you want better readability for column pairs in the client settings you can store keys instead and use the “get_cellByColumnKey” method where I went for indexes - because you know both on the server, and the key method will use it to find the index anyways.
All-in-one approach
This is the one if you need to keep everything in a single data cell. The all-in-one approach goes for a single data column holding the full state on the checkbox as a string just like you see it on the screenshots – “EnabledOn”, “EnabledOff” and so on. So you are once again in need of two columns, one checkbox and one hidden that carries the actual state. Cue similar set of event handlers to provide client side looks and behavior and you have a solution just as functional.
The grid markup, with variations for required bound and unbound fields, is essentially the same and so is the ‘disabling’ of checkboxes by checking their image source and canceling editing and initialize event handling. The main difference comes from the fact that setting state deals with and saves the full string values:
- // Sets the enabled/disabled state on the bound/unbound checkbox in the given cell
- function SetCheckState(cell, chkState, checkStateCell) {
- try {
- var checkState = chkState? chkState.replace("Enabled", "Disabled"): "";
- var checkBoxElem = cell.get_element().getElementsByTagName("img").item(0);
- var chkStates = checkStates[checkState];
- if (!chkStates) return;
- // Get the default values of src and title for checkbox in its enabled state
- var enabledSrc = null, enabledTitle = null;
- if (chkState && chkState.indexOf("Enabled") >= 0) {
- enabledSrc = "ig_res/Default/" + chkStates.src.replace("disabled_", "");
- enabledTitle = chkState.replace("Enabled", "").replace("On", "Checked").replace("Off", "Unchecked");
- }
- cell.set_value(chkStates.value, chkStates.chkState);
- checkBoxElem.src = enabledSrc? enabledSrc : chkStates.src;
- checkBoxElem.title = enabledTitle ? enabledTitle : chkStates.title;
- checkBoxElem.alt = enabledTitle ? enabledTitle : chkStates.alt;
- checkStateCell.set_value(chkState); // Store the new checkbox state value in the corresponding hidden checkbox
- }
- catch (ex) { }
- }
Bonus round
Of course, when I mention that you need two columns for this approach again, I mean that it won’t always be effective to bind a checkbox column to string values like “DisabledOn”. That doesn’t mean you can’t do it, though. Using the IBooleanConverter interface you can bind checkbox field (this naturally excludes unbound options) and it actually eases up the client code required as well because you won’t need the extra hidden column.
- publicclassCheckboxConverter : IBooleanConverter
- {
- publicobject DefaultFalseValue
- {
- get { return"EnabledOff"; }
- }
- publicobject DefaultTrueValue
- {
- get { return"EnabledOn"; }
- }
- publicbool IsFalse(object value)
- {
- return value.ToString().Contains("Off");
- }
- publicbool IsTrue(object value)
- {
- return value.ToString().Contains("On");
- }
- }
A bonus of the converter handling is that when editable checkboxes will set the default true/false values when the user interacts with them and use the rules to match checked or unchecked and when nothing matches ( read: “EnabledPartial”) it will actually set the checkbox to partial state as well. How convenient!
Options, options, options
I guess that is exactly what this blog can give you – 3 ways to achieve the Multiple enabled and disabled state checkbox functionality. Whether you want two Boolean columns that give a combined state or a single column approach with either hidden and presentation column pair or binding fields through a converter – all versions produce similar behavior with different amount of effort and limitations. It’s up to you to decide which one is a better fit for your requirements and reuse as much of the demo code as possible!
Speaking of code, here are the demo ASP.NET sites:
- Two Boolean columns – one Checkbox + one for flags
- Single data column with both hidden column and converter versions
Open as Web Site from Visual Studio or WebMatrix and you will need Infragistics ASP.NET installed (might need reference version adjustments) which you can grab from here:
I’d love to hear your thoughts, so leave a comment down below or ping me @DamyanPetev.
And as always, you can follow us on Twitter @Infragistics and stay in touch on Facebook, Google+ and LinkedIn!