Quantcast
Channel: DevExpress Support Center (Examples)
Viewing all 7205 articles
Browse latest View live

Form - Declare DropDownBox in a Form item


How to build binding paths in GridControl cells

$
0
0

Cell elements contain EditGridCellData objects in their DataContext.
Use the following binding paths to access cell values, columns, and ViewModel properties:

Value - access the current cell value;
Column - access the current column;
RowData.Row.[YourPropertyName] - access a property of an object from the ItemsSource collection;
Data.[FieldName] - access column values in Server Mode, access unbound column values;
View.DataContext.[YourPropertyName] - access a property in the grid's ViewModel.

The bindings we used in this example work as follows.

• Bind ComboBoxEdit.ItemsSource to the Countries property of the grid's ViewModel:
[XML]
<dxe:ComboBoxEditx:Name="PART_Editor"DisplayMember="Name"ItemsSource="{Binding View.DataContext.Countries}"/>

IMPORTANT: If you wish to assign the same ItemsSource collection to all editors in a column, use the EditSettings property instead of CellTemplate to gain better performance.

• Bind ComboBoxEdit.ItemsSource to the Cities properties stored at the item level:
[XML]
<dxe:ComboBoxEditx:Name="PART_Editor"ItemsSource="{Binding RowData.Row.Country.Cities}"/>
• Bind Button.Visibility to an unbound column value. The unbound column's FieldName is "Visited":
[XML]
<ButtonVisibility="{Binding Data.Visited, Converter={dx:BooleanToVisibilityConverter}}">Hide</Button>
• Bind ToolTip to display FieldName of the current column and a cell value:
[XML]
<SetterProperty="ToolTip"><Setter.Value><MultiBindingConverter="{local:CellTooltipConverter}"><BindingPath="Column.FieldName"/><BindingPath="Value"/></MultiBinding></Setter.Value></Setter>

IMPORTANT: You can use the CellToolTipBinding property to specify a tooltip for grid cells.

• Bind cells' Background to the Color properties stored at the item level:
[XML]
<!-- xmlns:dxmvvm="http://schemas.devexpress.com/winfx/2008/xaml/mvvm"; --><Style.Triggers><TriggerProperty="SelectionState"Value="None"><SetterProperty="Background"Value="{Binding RowData.Row.Color, Converter={dxmvvm:ColorToBrushConverter}}"/></Trigger></Style.Triggers>

See also:

How to build binding paths in GridControl rows

How to build binding paths in GridControl rows

$
0
0

Row elements contain RowData objects in their DataContext. Use the following binding paths to access cell values and ViewModel properties:

Row.[YourPropertyName] - accesses a property of an object in the ItemsSource collection (see RowData.Row);
DataContext.[FieldName] - accesses column values in Server Mode, accesses unbound column values (see RowData.DataContext);
View.DataContext.[YourPropertyName] - accesses a property in the grid's ViewModel (see RowDataBase.View).

The bindings we used in this example work as follows.

• Bind rows' Background to the Color properties stored at the item level:
[XML]
<TriggerProperty="SelectionState"Value="None"><SetterProperty="Background"Value="{Binding Row.Color, Converter={dxmvvm:ColorToBrushConverter}}"/></Trigger>
• Highlight a row when the HighlightVisited property of the grid's ViewModel and the Visited column value are true.
[XML]
<MultiDataTrigger><MultiDataTrigger.Conditions><ConditionBinding="{Binding View.DataContext.HighlightVisited}"Value="True"/><ConditionBinding="{Binding DataContext.Visited}"Value="True"/></MultiDataTrigger.Conditions><SetterProperty="TextElement.FontStyle"Value="Italic"/><SetterProperty="TextElement.FontWeight"Value="Bold"/></MultiDataTrigger>

See also:

How to build binding paths in GridControl cells

ASPxGridView - How to export a colored grid when the Data Aware export mode is used

$
0
0

UPDATED:

Starting with version v2015 vol 2 (v15.2), this functionality is available out of the box. Use ASPxGridView.FormatCondition rules to define conditional formatting in Browse Mode and keep the applied appearance in the Exported Document. Please refer to the ASP.NET Grid View - Data Range Filter, Adaptivity and More (Coming soon in v15.2) blog post and the Export with Format Conditions demo for more information.
If you have version v15.2+ available, consider using the built-in functionality instead of the approach detailed below.

If you need to apply custom appearance in the Exported Document only or define fine tuned complex appearance (for instance, based on some runtime calculated values, custom business rules, etc.), use the CsvExportOptionsEx / XlsExportOptionsEx / XlsxExportOptionsEx CustomizeCell event in the Data Aware export mode.

In v2014 vol 2, we introduced the Excel Data Aware Export feature into our grid. While this feature significantly improves the export capabilities (see the New Excel Data Export Engine blog post), it also has some limitations. Most of them are described in the T186064: ASPxGridView / MVC GridView Extension - Excel Data Aware Export FAQ article.
One of them is that the ASPxGridViewExporter.RenderBrick event is not raised when the data-aware export is used. Commonly, this event is used for customizing the cell appearance in resulted documents (a back color, fonts, a format, etc.). While this event is not available, it is still possible to accomplish this task. The XlsxExportOptionsEx object provides the CustomizeCell event that can be used for customizing cells in the exported document:

[C#]
varexportOptions=newXlsxExportOptionsEx();exportOptions.CustomizeCell+=exportOptions_CustomizeCell;ASPxGridViewExporter1.WriteXlsxToResponse(exportOptions);...voidexportOptions_CustomizeCell(DevExpress.Export.CustomizeCellEventArgsea){if(ea.ColumnFieldName!="UnitsOnOrder")return;if(Convert.ToInt32(ea.Value)== 0)ea.Formatting.BackColor=Color.Salmon;elseea.Formatting.BackColor=Color.LightGray;ea.Handled=true;}
[VB.NET]
Dim exportOptions = New XlsxExportOptionsEx() AddHandler exportOptions.CustomizeCell, AddressOf exportOptions_CustomizeCell ASPxGridViewExporter1.WriteXlsxToResponse(exportOptions) ... PrivateSub exportOptions_CustomizeCell(ByVal ea As DevExpress.Export.CustomizeCellEventArgs) If ea.ColumnFieldName <> "UnitsOnOrder"ThenReturnEndIfIf Convert.ToInt32(ea.Value) = 0 Then ea.Formatting.BackColor = Color.Salmon Else ea.Formatting.BackColor = Color.LightGray EndIf ea.Handled = TrueEndSub

This example illustrates a sample scenario with exporting a colored grid when the Data Aware export mode is used.

See Also:
How to export the colored ASPxGridView

ASPxGridView - How to implement a custom ASP.NET control like MemoEdit in DataItemTemplate

$
0
0

This example demonstrates how to implement a custom ASP.NET control like MemoEdit in the DataItemTemplate in two different ways - in markup and code behind.

A markup way

Use these steps:

1. Add the ASPxDropDownEdit control to the DataItemTemplate of a column and configure it.
2. Add two custom buttons (Save and Cancel) and the ASPxMemo control to the ASPxDropDownEdit.DropDownWindowTemplate.
3. Handle the Load  event of the ASPxDropDownEdit and ASPxMemo controls. In this event handler, get a visible index of the current row (use the approach from The general technique of using the Init/Load event handler). Set a unique ClientInstanceName property based on that visible index.
4. In the Load event handler of the dropdown, add the column's value to the dropdown. Add the JSProperties property to get an index of the dropdown on the client side.
5. Add two global variables. Use the Init event handler to change the visibility of the background image. In the DropDown event, set the current value to the memo. Use the OnSaveClick and OnCancelClick handlers of the ASPxClientButton.Click event to save and hide the dropdown:
[JavaScript]
var dropDownEdit;var memo;function OnDropDown(s, e){ SetGlobalVariables(s); memo.SetText(dropDownEdit.GetValue());}function OnCancelClick(s, e){ dropDownEdit.HideDropDown();}function OnSaveClick(s, e){ dropDownEdit.SetValue(memo.GetValue()); SetInputDisplayFormat(dropDownEdit); dropDownEdit.HideDropDown();}function SetInputDisplayFormat(dde){var input = dde.GetInputElement(); input.style.display = (input.value != "") ? "none" : "block";}function SetGlobalVariables(dde){ dropDownEdit = dde; memo = ASPxClientControl.GetControlCollection().GetByName("memo_" + dde.cpIndex);}
6. Add the following CSS rules on the page and assign the CSS class to the ASPxMemo control:
[CSS]
.memotextarea{padding:0px!important;resize:both;margin:0px!important;}.memotd{padding:0px!important;}

This workaround adds the resize "grip"  at the bottom right of this control.

A code-behind way

Use the following steps:

1. In code behind, add two ITemplate classes. The first class will implement a template for the grid, the second - for the dropdown.
2. Handle the DataBinding event of the grid. In the event handler, add the first class instance to the target column.
3. In the first class, define ASPxDropDownEdit  (based on The general technique of using the Init/Load event handler) and find a visible index (use the approach from the How to create controls dynamically KB article). Define all the necessary properties. Create a unique ID and ClientInstanceName based on the visible index and handle client-side events. Add the JSProperties property to get an index of the dropdown on the client side. Add the second class instance to the ASPxDropDownEdit.DropDownWindowTemplate.
4. Add the constructor and a private variable to the second class to take the container of the dropdown to define a visible index.
5. In the second class, define ASPxMemo and two buttons. Find a visible index of the grid. Define all the necessary properties. Create a unique ID and ClientInstanceName based on the visible index and handle client-side events.
6. Repeat steps 5 and 6 from the approach with markup.

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)
Default2.aspx (VB: Default2.aspx)
Default2.aspx.cs (VB: Default2.aspx.vb)
Default3.aspx (VB: Default3.aspx)
Default3.aspx.cs (VB: Default3.aspx.vb)

ASPxGridView - How to implement cascading combo boxes in Batch Edit mode by using WebMethods

$
0
0

This example shows how to implement cascading combo boxes in EditingSettings "Batch" mode by using WebMethods. The example is based on ASPxGridView - How to implement cascading comboboxes in Batch Edit mode and How to populate a cascading ASPxComboBox by using WebMethods examples. The main idea is to remove EditTemplate from ASPxGridView and replace the ASPxComboBox Callback by WebMethods to refresh the child's combo box item collection. This will improve the server's response time and reduce the server's load.

See also:
ASPxGridView - How to implement cascading comboboxes in Batch Edit mode

Files to look at:

DataProvider.cs (VB: DataProvider.vb)
Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)
JavaScript.js (VB: JavaScript.js)

ASPxGridView - How to implement instant editing with check boxes in columns

$
0
0

This example illustrates how to implement instant editing in ASPxGridView. It is divided in two independent samples:

- The first sample (the Default1 page) illustrates how to post modified data to the underlying database on demand. Note that starting with v2013 vol 2, we provide a similar feature out-of-the-box: Batch Edit Mode.
- The second sample (the Default2 page) illustrates how to post modified data to the underlying database immediately.

In both samples, we define a custom GridViewDataColumn.DataItemTemplate with ASPxCheckBox. We handle the ASPxCheckBox' Init event (see The general technique of using the Init/Load event handler) to generate client-side ASPxClientCheckBox.CheckedChanged Event handler dynamically based on the current filed name and row key:

[C#]
// Default1.aspx.cs protectedvoidcb_Init(objectsender,EventArgse){ASPxCheckBoxcheckBox=(ASPxCheckBox)sender;GridViewDataItemTemplateContainercontainer=(GridViewDataItemTemplateContainer)checkBox.NamingContainer;stringkey=string.Format("{0}_{1}",container.Column.FieldName,container.KeyValue);checkBox.ClientSideEvents.CheckedChanged=string.Format("function(s, e) {{ hf.Set('{0}', s.GetChecked()); }}",key);}// Default2.aspx.cs protectedvoidcb_Init(objectsender,EventArgse){ASPxCheckBoxcheckBox=(ASPxCheckBox)sender;GridViewDataItemTemplateContainercontainer=(GridViewDataItemTemplateContainer)checkBox.NamingContainer;stringkey=string.Format("{0}|{1}",container.Column.FieldName,container.KeyValue);checkBox.ClientSideEvents.CheckedChanged=string.Format("function(s, e) {{ grid.PerformCallback('{0}|' + s.GetChecked()); }}",key);}

As you can see, in the first case we just save the modified value to the hidden field via the ASPxClientHiddenField.Set Method. These values will be extracted from it and posted to the database later when the "Save Changes" button is clicked. In the second case, we immediately initiate a saving callback via the ASPxClientGridView.PerformCallback Method.

See Also:
How to perform ASPxGridView instant updating using different editors in the DataItem template
How to implement the multi-edit functionality with a multi-page grid that is bound dynamically

Files to look at:

Default.aspx (VB: Default.aspx)
Default1.aspx (VB: Default1.aspx)
Default1.aspx.cs (VB: Default1.aspx.vb)
Default2.aspx (VB: Default2.aspx)
Default2.aspx.cs (VB: Default2.aspx.vb)

ASPxGridView - How to implement search in the Column Chooser window

$
0
0

This example illustrates how to add an input element to the Column Chooser window and filter columns in this window.
First of all, create an input element and append it to the Column Chooser dom elements:

[JavaScript]
var _createElement = function(tag, parent){var element = document.createElement(tag);if(parent) parent.appendChild(element);return element;} that.appendToDom = function(){var tr = _createElement("tr"); tr.id = containerID;var td = _createElement("td", tr);var inputContainer = _createElement("div", td); inputContainer.id = extensionID;var inputElement = _createElement("input", inputContainer); inputElement.type = "text"; inputElement.onchange = that.onchange; inputElement.value = that.lastValue;if(inputElement.value) inputElement.onchange();var parent = that._getTable(); parent.insertBefore(tr, parent.children[0]);}

Note, that to correctly append the input element to the Column Chooser window, handle the client-side Init and EndCallback events and add the input element there.
After that, handle the onchange event and search for a typed value through the html table that contains field names:

[JavaScript]
that.onchange = function(){var newText = this.value.toLowerCase();var children = that._getTable().children;for(var i = 0, l = children.length; i < l; i++){var _tr = children[i];if(_tr.id == containerID)continue; _tr.classList.remove(hideClass);var _tds = []; _findChildren(_tr.children, "td", _tds)var hasText = _tds.filter(function(item){return item.textContent.toLowerCase().indexOf(newText)> -1 }).length > 0;if(!hasText) _tr.classList.add(hideClass);} that.lastValue = newText;}

It is possible to hide a row with a field name that doesn't contain the typed text by setting a certain CSS class to the row element:

[CSS]
tr.cw-hide{display:none;}

Files to look at:

AppClientCode.js (VB: AppClientCode.js)
Default.aspx (VB: Default.aspx)

ASPxGridView - How to make field editors read-only/editable when editing or adding a row

$
0
0

This example demonstrates how to set the editor's ReadOnly property based on the grid's state. That is, it is possible to edit a field value while adding a new row, but this editor becomes ReadOnly on an attempt to edit the existing row.

It is used the ASPxGridView.CellEditorInitialize event to implement this scenario:
Starting with version 14.2:

[C#]
protectedvoidgridView_CellEditorInitialize(objectsender,DevExpress.Web.ASPxGridViewEditorEventArgse){ASPxGridViewgrid=senderasASPxGridView;if(e.Column.FieldName=="CategoryID")e.Editor.ReadOnly=!grid.IsNewRowEditing;}

For older versions:

[C#]
protectedvoidgridView_CellEditorInitialize(objectsender,DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgse){ASPxGridViewgrid=senderasASPxGridView;if(e.Column.FieldName=="CategoryID")e.Editor.ReadOnly=!grid.IsNewRowEditing;}

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to save selected rows to the database by using WebMethods

$
0
0

This example shows how to save and retrieve selection state of the row. It is realized by using WebMethods. On page loading, selection state is retrieved from the database and ASPxGridView rows are selected by the SetSelection method. When a row is selected, the client-side ASPxClientGridView.SelectionChanged event is raised and the UpdateDB method is called. This method updates a database.
On the client side, WebMethod is called by

[JavaScript]
PageMethods.UpdateDB(array);

On the server side, ScriptManager is used with EnablePageMethods set in "True".

[ASPx]
<asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true"></asp:ScriptManager>

and the C# method is marked by WebMethodAttribute

[C#]
usingSystem.Web.Services; [WebMethod]publicstaticvoidUpdateDB(object[]array){//method code }

See also:
ASPxGridView - How to save selected rows to the database when ProcessSelectionChangedOnServer is True
How to track progress of server side processing on the client side (using WebMethods)

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to undo changes for a cell in Batch Edit Mode

$
0
0

This example demonstrates two approaches to reset cell changes.

1. It is allowed to reset changes for a cell via the context menu item.
2. It is possible to undo the last change of the modified cell value using 'Ctrl+Z' hot keys.
For detailed information, see Implementation Details.
If you wish to use both approaches at once in your project, you need to synchronize the changedCells stack from the 'HotKey' approach with actual cells that were changed after resetting a value via the context menu item.
Description 1. The Context Menu approach
Add an item to the context menu in the ASPxGridView.FillContextMenuItems event handler as follows:
[C#]
protectedvoidGrid_FillContextMenuItems(objectsender,DevExpress.Web.ASPxGridViewContextMenuEventArgse){if(e.MenuType==DevExpress.Web.GridViewContextMenuType.Rows){e.Items.Add(e.CreateItem("Reset Changes","reset_cell"));}}

To identify each cell, add the "oncontextmenu" attribute for every cell and send its column index to the client-side function as shown below:

[C#]
protectedvoidGrid_HtmlDataCellPrepared(objectsender,DevExpress.Web.ASPxGridViewTableDataCellEventArgse){e.Cell.Attributes.Add("oncontextmenu","onCellRightBtnClick("+e.DataColumn.Index+")");}

On the client side, there are two functions (onCellRightBtnClickonContextItemClick) and one global variable (clickedColumnIndex).

The onContextItemClick function is a handler of the ASPxClientGridView.ContextMenuItemClick event.
The clickedColumnIndex variable is used as a parameter of the ASPxClientCardViewBatchEditApi.ResetChanges(Int32,Int32) method.

2. The Hot Keys approach
It is implemented fully on the client side. The main idea is to store changed cells in a stack and remove a value if the 'Ctrl + Z' combination is performed.
A cell is initialized in the client-side BatchEditStartEditing event. In the client-side BatchEditEndEditing event, the modified cell is added to the stack.
For new rows, a value is pushed into the stack once for each new row. Further cells changes in new rows won't be stored in the stack.
If a cell gets its old value, there is no need to keep it in the stack. The removeCellFromStack function is used for this purpose.

Files to look at:

GridDataItem.cs (VB: GridDataItem.vb)
ContextMenu.aspx (VB: ContextMenu.aspx)
ContextMenu.aspx.cs (VB: ContextMenu.aspx.vb)
Default.aspx (VB: Default.aspx)
HotKeys.aspx (VB: HotKeys.aspx)
HotKeys.aspx.cs (VB: HotKeys.aspx.vb)

ASPxGridView - How to turn off automatic auto filter row processing

$
0
0

This example demonstrates how to turn off the automatic auto filter row processing and perform the filtering of all rows simultaneously by a button click. Perform the following steps to implement this scenario:

1. Remove the standard client-side ValueChanged and KeyDown event handlers for the filter row editors and create the custom handler. Use the ASPxClientEvent.ClearHandlers and ASPxClientEvent.AddHandler methods for this purpose:
[C#]
protectedvoidgv_AutoFilterCellEditorInitialize(objectsender,DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgse){ASPxTextBoxeditor=e.EditorasASPxTextBox;if(editor!=null){editor.ClientSideEvents.Init="function(s, e) { s.ValueChanged.ClearHandlers(); s.KeyDown.ClearHandlers(); s.KeyDown.AddHandler( function(s, e) { if(e.htmlEvent.keyCode ==13) ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);} ); }";editor.ClientInstanceName="filterRow_"+e.Column.FieldName;}}
[VB.NET]
ProtectedSub gv_AutoFilterCellEditorInitialize(ByVal sender AsObject, ByVal e As DevExpress.Web.ASPxGridView.ASPxGridViewEditorEventArgs) Dim editor As ASPxTextBox = TryCast(e.Editor, ASPxTextBox) If editor IsNot NothingThen editor.ClientSideEvents.Init = "function(s, e) { s.ValueChanged.ClearHandlers(); s.KeyDown.ClearHandlers(); s.KeyDown.AddHandler( function(s, e) { if(e.htmlEvent.keyCode ==13) ASPxClientUtils.PreventEventAndBubble(e.htmlEvent); } ) ; } " editor.ClientInstanceName = "filterRow_"& e.Column.FieldName EndIfEndSub
2. Now, when automatic filter is processing is turned off, it is necessary to perform filtering manually via the ASPxClientGridView.ApplyFilter method:
[JavaScript]
function ApplyFilter(){var filterCondition = "";var andOperator = "";for(var i = 0; i < gridViewR.GetColumnsCount(); i++)if(gridViewR.GetAutoFilterEditor(i) != null){if(filterCondition != "") andOperator = "And "var editor = eval("filterRow_" + gridViewR.GetColumn(i).fieldName);if(editor)if(editor.GetText() != "") filterCondition = filterCondition + andOperator + "Contains( [" + gridViewR.GetColumn(i).fieldName + "]," + "'" + editor.GetText() + "')";} gridViewR.ApplyFilter(filterCondition);}

Update:
Starting with version v2013 vol 2.5, we have implemented the new 'on click' filter mode. In this mode, a filter is applied to the grid by clicking the Apply button, which is displayed in a command column.

To provide your application with this functionality, display the filter row in the grid by setting the ShowFilterRow property to true and set the FilterRowMode property to OnClick.

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to store a focused row index in cookies

$
0
0

ASPxGridView does not save a focused row in cookies. However, you can add this capability by saving and restoring a focused row index to cookies manually:

[JavaScript]
function OnFocusedRowChanged(s, e){ ASPxClientUtils.SetCookie(s.name + '_focudedIndex', s.GetFocusedRowIndex());}function OnInit(s, e){if(ASPxClientUtils.GetCookie(s.name + '_focudedIndex') != null) s.SetFocusedRowIndex(ASPxClientUtils.GetCookie(s.name + '_focudedIndex'));}

See Also:
ASPxGridView - How to store a focused row index in cookies when ProcessFocusedRowChangedOnServer="true"

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to show the number of selected rows in the Pager bar

$
0
0

This example demonstrates how to show the number of selected rows in the Pager bar. It is necessary to create a custom PagerBar template for this purpose. This template will contain ASPxLabel that allows showing the number of selected rows and a standard pager created via the ASPxGridViewTemplateReplacement control:

[ASPx]
<PagerBar><table><tr><td><dx:ASPxGridViewTemplateReplacementrunat="server"ReplacementType="Pager"/></td><td><dx:ASPxLabelID="labelInfo"runat="server"Text=""ClientInstanceName="labelInfo"></dx:ASPxLabel></td></tr></table></PagerBar>

We can get the grid's selected row count via the client-side ASPxClientGridView.GetSelectedRowCount method and then set it to ASPxLabel using the label's SetText method:

[JavaScript]
function ShowRowsCount(){ labelInfo.SetText('Selected rows count: ' + gridView.GetSelectedRowCount());}

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to show the live data without refreshing the grid (using WebMethods)

$
0
0

This example demonstrates how to update data only for several (or all, if it is required) grid columns without refreshing the entire grid. The main idea is to create a custom DataItem template for the required columns and then update its data on the client side. The server-side values can be obtained without the grid callback by using WebMethods.

See Implementation Details** for more information.

See also:
How to display dynamic data within the ASPxGridView (Live Data) without full grid updating using the ASPxCallback control

Description

To implement this task, add a custom DataItem template with ASPxLabel (or another control corresponding to the column type) for the column that should be updated:

[ASPx]
<dx:GridViewDataSpinEditColumnFieldName="C2"Caption="Numeric (Live)"><DataItemTemplate><dx:ASPxLabelID="labelC1"runat="server"Text='<%# Eval("C2") %>'OnInit="labelC1_Init"></dx:ASPxLabel></DataItemTemplate></dx:GridViewDataSpinEditColumn>

 Then, specify the label's ClientInstanceName property based on the row key:

[C#]
protectedvoidlabelC1_Init(objectsender,EventArgse){ASPxLabellabel=senderasASPxLabel;GridViewDataItemTemplateContainercontainer=label.NamingContainerasGridViewDataItemTemplateContainer;label.ClientInstanceName="labelC1_"+container.KeyValue;}

 Please refer to the KB article for more information about this technique.

After that, call the server-side request to get updated values and pass them to the client side, for example, in the json format:

[JavaScript]
PageMethods.GetUpdatedDataFromServer(keys, onSucess, onError);
[C#]
[WebMethod]publicstaticstringGetUpdatedDataFromServer(int[]keys){...List<GridDataItem>GridData=GetDataSource();List<GridDataItem>newDataRequiredForClient=newList<GridDataItem>();

}

 Finally, update that data on the client side or generate the error (in case of any exception):

[JavaScript]
function onSucess(result){var items = JSON.parse(result);for(var i = 0; i < items.length; i++){var label = ASPxClientControl.GetControlCollection().GetByName("labelC1_" + items[i].ID); label.SetText(items[i].C2);...}}
function onError(result) {  

alert('Something wrong!');  

}  

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to show the command or custom button only for hovered rows

$
0
0

This example demonstrated how to show the command button or a custom button placed inside the DataItem template only for the hovered rows when the ASPxGridView.SettingsBehavior.EnableRowHotTrack property is enabled.

Description

The main idea is that it is necessary to hide the required button using CSS. For example:

[CSS]
.hottrackButton{visibility:hidden;}
[ASPx]
<SettingsCommandButton><EditButtonRenderMode="Image"Image-IconID="edit_edit_32x32"><Styles><StyleCssClass="hottrackButton"></Style></Styles></EditButton> ...</NewButton></SettingsCommandButton>

or:

[ASPx]
<DataItemTemplate> ... <dx:ASPxButtonID="btDelete"runat="server"...CssClass="hottrackButton"> ... </dx:ASPxButton></DataItemTemplate>

Then, add the custom CSS class to the RowHotTrack property:

[ASPx]
<Styles><RowHotTrackCssClass="hottrackRow"></RowHotTrack></Styles>

This way, you will be able to show the required buttons only when they are hovered:

[CSS]
.hottrackRow.hottrackButton{visibility:visible;}

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

ASPxGridView - How to show ASPxPopupControl as a tooltip for the grid cells

$
0
0

This example illustrates how to show ASPxPopupControl instead of a standard cell tooltip.

Description

To implement this task, perform the following steps:

1. Create ASPxPopupControl with ASPxLabel inside:
[ASPx]
<dx:ASPxPopupControlID="ASPxPopupControl1"runat="server"ClientInstanceName="popup"ShowHeader="false"><ContentCollection><dx:PopupControlContentControlrunat="server"><dx:ASPxLabelID="ASPxLabel1"runat="server"Text="ASPxLabel"ClientInstanceName="lbl"></dx:ASPxLabel></dx:PopupControlContentControl></ContentCollection></dx:ASPxPopupControl>
2. Handle the ASPxGridView.HtmlDataCellPrepared event to add the **mouseover**event handler for the grid cells:
[C#]
protectedvoidgridView_HtmlDataCellPrepared(objectsender,DevExpress.Web.ASPxGridViewTableDataCellEventArgse){e.Cell.Attributes.Add("onmouseover",string.Format("onShowPopup(event.x, event.y, '{0}')",e.GetValue("Description")));}
3. Then, you will be able to show a popup with the required information
[JavaScript]
function onShowPopup(x, y, text){ lbl.SetText(text); popup.ShowAtPos(x, y);}

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

BootstrapGridView - Batch Edit mode - How to edit CheckBox column in a single click

$
0
0

Starting with v17.1.4 and v17.2.3, BootstrapGridView provides the AlwaysShowCheckboxesInCheckColumns property. To achieve the desired behavior, use the following code:

<SettingsEditing><BatchEditSettings AlwaysShowCheckboxesInCheckColumns="true" /></SettingsEditing>

Files to look at:

Default.aspx (VB: Default.aspx)
Default.aspx.cs (VB: Default.aspx.vb)

GridView - How to drag and drop items from one grid to another

$
0
0

The example demonstrates how to use the jQuery framework to drag an item from one grid to another.

- Use jQuery UI Draggable and Droppable plug-ins;
- Define "draggable" and "droppable" items:

[C#]
settings.Styles.Table.CssClass="droppableRight";settings.Styles.Row.CssClass="draggableRow right";

- Initialize the defined draggable/droppable items via the corresponding jQuery selectors. The "start" event handler can be used to obtain the key of the dragged row and apply conditional styling to it:

[JavaScript]
start: function(ev, ui){var $sourceElement = $(ui.helper.context);var $draggingElement = $(ui.helper);var sourceGrid = ASPxClientGridView.Cast($draggingElement.hasClass("left") ? "gridOne" : "gridTwo");//style elements $sourceElement.addClass("draggingStyle"); $draggingElement.addClass("draggingStyle"); $draggingElement.width(sourceGrid.GetWidth());//find key rowKey = sourceGrid.GetRowKey($sourceElement.index() - 1);},

- Handle the "drop" event of the "droppable" items and perform a callback to the callback panel that has both grids nested inside to perform the data editing functionality.

Select the "script.js" source file and review the comments to find an illustration of the above steps.

See Also:
How to use jQuery to drag and drop items from one ASPxGridView to another
Files to look at:

HomeController.cs (VB: HomeController.vb)
GridModel.cs (VB: GridModel.vb)
script.js (VB: script.js)
_CallbackPanelPartial.cshtml
_GridOne.cshtml
_Grids.cshtml
_GridTwo.cshtml
Index.cshtml

GridView - How to display a hyperlink in templated column

$
0
0

This example illustrates how to use the MVCxGridViewColumn.SetDataItemTemplateContent(Action`1) Method to display a hyperlink in a specific column. The hyperlink parameters (text, navigate url) are calculated based on the template's container. Here is the most important part of the code that is responsible for hyperlink creation:

[C#]
settings.Columns.Add(column=>{column.Caption="Details";column.SetDataItemTemplateContent(container=>{Html.DevExpress().HyperLink(hyperlink=>{varvisibleIndex=container.VisibleIndex;varkeyValue=container.KeyValue;varlastName=DataBinder.Eval(container.DataItem,"LastName");hyperlink.Name="hl"+keyValue.ToString();hyperlink.Properties.Text=lastName.ToString();hyperlink.NavigateUrl=Url.Action("Details","Home",new{id=keyValue});}).Render();});});
[VB.NET]
settings.Columns.Add( _ Sub(column) column.Caption = "Details" column.SetDataItemTemplateContent( _ Sub(container) Html.DevExpress().HyperLink( _ Sub(hl) Dim visibleIndex = container.VisibleIndex Dim keyValue = container.KeyValue Dim lastName = DataBinder.Eval(container.DataItem, "LastName") hl.Name = "hl" + keyValue.ToString() hl.Properties.Text = lastName.ToString() hl.NavigateUrl = Url.Action("Details", "Home", NewWith {.id = keyValue}) EndSub).Render() EndSub) EndSub)

Files to look at:

HomeController.cs (VB: HomeController.vb)
Details.cshtml
GridViewPartial.cshtml
Index.cshtml
Viewing all 7205 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>