Moving from DataGridView
NoxGrid uses the DataGridView names wherever it can, so most code moves over by renaming the type. This page lists what maps one to one, what works differently, and the few behaviors that are guaranteed.
Properties and methods
| DataGridView | NoxGrid |
|---|---|
DataSource, DataMember, AutoGenerateColumns |
the same |
Columns.Add, column DataPropertyName, HeaderText, Width, MinimumWidth, Visible, ReadOnly, Frozen, FillWeight, SortMode, Tag |
the same |
DataGridViewTextBoxColumn · CheckBoxColumn · ComboBoxColumn · ButtonColumn · ImageColumn |
NoxGridColumn · NoxGridCheckBoxColumn · NoxGridComboBoxColumn · NoxGridButtonColumn · NoxGridImageColumn (also number, date, label and progress columns) |
combo column DataSource, DisplayMember, ValueMember |
the same |
DataGridViewComboBoxCell.DataSource / .Items (a list per cell) |
Cells(r, c).ComboItems or the CellComboItemsNeeded event |
Rows(i), Rows.Add, Rows.RemoveAt, Rows.Clear, Rows(i).DataBoundItem, Rows(i).Tag, Rows(i).IsNewRow, Rows(i).Index, For Each row In Rows |
the same (the row type is NoxGridRow; Rows.Cast(Of NoxGridRow) works); also Rows.Remove(row), Rows.RemoveRows(rows), Rows.RemoveAll(condition), Rows(i).Key, Rows.IndexOfKey |
Rows(i).Cells(c).Value, Rows(i).Cells("name").Value |
different: a row has no Cells; read and write values directly with row(c) or row("name"). Cell objects: grid.Cells(r, c), grid.Cells(r, "name") |
SelectedCells, Cells(r, c).Selected = True, selecting a whole column |
no SelectedCells collection. Check with IsCellSelected(r, c), IsRowSelected(r), GetSelectedRows(), SelectedCellCount; select with SelectRange(r1, c1, r2, c2) (a whole column: SelectRange(0, c, RowCount - 1, c)), SelectRow(r, add), SelectAll(), ClearSelection(). Cells(r, c).Selected is read-only |
ClipboardCopyMode |
CopyIncludesHeaders (headers always when on). There is no copy event: to decide per copy, handle Ctrl+C yourself and use GetClipboardText(includeHeaders) |
CurrentCell, CurrentRow, SelectedRows, SetCurrentCell |
CurrentCell, CurrentRowIndex, CurrentColumnIndex, GetSelectedRows(), SetCurrentCell(row, column) |
FirstDisplayedScrollingRowIndex, HorizontalScrollingOffset |
FirstDisplayedRowIndex, HorizontalScrollingOffset |
AllowUserToAddRows, DeleteKeyAction (instead of AllowUserToDeleteRows), AllowUserToResizeColumns, AllowUserToOrderColumns, MultiSelect, SelectionMode (CellSelect, FullRowSelect, RowHeaderSelect), EditMode |
the same |
AutoSizeRowsMode (AllCells, DisplayedCells) |
the same |
AlternatingRowsDefaultCellStyle.BackColor, DefaultCellStyle.SelectionBackColor, GridColor, ColumnHeadersDefaultCellStyle |
AlternatingRowBackColor, SelectionBackColor, GridLineColor, HeaderBackColor, HeaderForeColor, HeaderFont; or a whole ColorScheme |
CellStyle.Padding |
CellPadding |
ColumnHeadersDefaultCellStyle.WrapMode (DataGridView wraps by default) |
HeaderWrapText (off by default); or HeaderTextFit = ShrinkText to draw a long header smaller on one line |
setting the edit box ReadOnly in EditingControlShowing so a cell can be selected and copied |
column ReadOnly = True with ReadOnlyMode = Selectable (F2 or double-click opens a read-only edit box) |
refusing some ways of opening the edit box in CellBeginEdit |
column EditTrigger (F2OrDoubleClick, DoubleClickOnly, Never), or e.StartReason in CellBeginEdit |
| clearing unbound cells by hand after binding again | ClearUnboundValues() |
BeginEdit, EndEdit, CancelEdit, EditingControl, IsCurrentCellInEditMode |
the same |
| ADGV (Advanced DataGridView) filter and sort menus | AllowFiltering (filter popup per column), header sorting, SortCycle = AscendingDescendingNone |
| saving column widths and order yourself | GetLayout() / ApplyLayout(text) |
| saving theme colors yourself | GetColorSettings() / ApplyColorSettings(text) |
Events
| DataGridView | NoxGrid |
|---|---|
CellClick, CellDoubleClick, CellValueChanged, CellValidating, CellBeginEdit, CellEndEdit, CellFormatting, CellPainting, CellToolTipTextNeeded, EditingControlShowing, DataError |
the same |
CellMouseDown, CellMouseUp, CellMouseClick, CellMouseDoubleClick, CellMouseMove, CellMouseEnter, CellMouseLeave |
the same (e.Handled on CellMouseDown skips the grid's own handling) |
CellContentClick, CellContentDoubleClick, GetCellContentBounds (cell ContentBounds) |
the same: only the check box, the button, the text or the picture of the cell, and Space on a check box or button cell |
ColumnHeaderMouseClick, RowHeaderMouseClick |
the same (e.Handled on ColumnHeaderMouseClick skips sorting) |
CurrentCellChanged, SelectionChanged, RowsAdded, RowsRemoved, Sorted, Scroll, ColumnWidthChanged |
the same, plus CurrentRowChanged |
SortCompare |
the same (unbound grid), plus e.SortOrder; see Sorting |
DataBindingComplete, DefaultValuesNeeded, UserAddedRow, UserDeletingRow, UserDeletedRow |
the same |
ColumnStateChanged (visibility) |
ColumnVisibleChanged |
CurrentCellDirtyStateChanged + CommitEdit for check boxes |
not needed: a check box click is committed at once |
| (none) | CellPasting and Pasted for pasting, HeaderCheckChanging and HeaderCheckChanged for the header check box, FooterValueNeeded for the footer row |
Notes on events:
CellBeginEdithase.StartReason(Keystroke,F2,DropDownKey,DoubleClick,Click,Enter,Code) ande.IsReadOnlyEdit.- Binding different data clears the filters. Changing
DataSourceorDataMemberclears the header filters, as it clears the sort, and raisesFilterChanged. Rows added or changed in the same data keep the filters. - Finding columns by name:
grid(r, "name"),row("name")andCells(r, "name")look up the columnNamefirst, thenDataPropertyName. - Filtered-out rows stay in
Rows. Filtering only hides rows on screen; it does not change the boundDataTableorDataViewRowFilter.Rows.CountandFor Eachinclude every row;row.FilteredOut,row.DisplayedandVisibleRowCounttell what is shown. To save regardless of the filter, read the boundDataTable. - Paste rules: pasting starts at the current cell; hidden columns and rows are skipped and the paste continues in the next visible column or row. Read-only cells keep their position and their value is dropped (later values are not shifted left). Lines beyond the last row are dropped and reported by
Pasted'sDroppedRowCount; withPasteAddsRows = True(unbound) the missing rows are added (same undo step, defaults fromDefaultValuesNeeded). A cell that breaks a boundDataTableconstraint is reverted,DataErroris raised and the paste continues with the next cell. CellValueChanged: a value your handler sets (for example a computed amount after the user typed a quantity) raises the event again with the reason of the first change (UserEdithere) ande.IsNested = True. Skip it withIf e.IsNested Then Return, instead of a loading flag. The user's change and your handler's changes are undone together, and undo and redo raise the handler's changes again withIsNested = True.ColumnHeaderMouseClickcomes for the right button too (to show your own menu). Only the left button sorts.DataError:e.Columnis always set.e.RowIndexis -1 when the error comes from a header (ColumnHeaderPainting, a header tooltip) or the footer row (FooterValueNeeded).CellFormattingcan change the text, colors and bold (FormattedValue,BackColor,ForeColor,Bold, selection colors). For a different font or alignment use the column'sFontandAlignmentor the cell's style.
What works differently
- No first row is selected after binding. Set
SelectFirstRowOnBind = Truefor master-detail screens. It also works when onlyBindingSource.DataSourceis replaced. - Row objects follow their row. A
Rows(i)you keep stays on the same data row after inserts, removals and sorting. When the row is removed,IsRemovedis True and using it throws. - Check boxes commit at once. Remove
CellContentClicktoggling,CommitEditandCurrentCellDirtyStateChangedcode, or the value changes twice. KeepCellContentClickfor what the app does after a click (it still comes only for clicks on the check box itself). - A check box toggles when any part of its cell is clicked (DataGridView: only the box). To react only to the box, use
CellContentClick. - Ctrl+click and Shift+click on a check box cell only extend the selection; the check box does not change. Set the column's
ToggleWithModifierKeys = Trueto toggle it as DataGridView does.CellContentClickcomes either way. - Clicking three times quickly: the second press is a double-click (
CellDoubleClick,CellContentDoubleClick), the third press is a click again (CellClick,CellContentClick), as in DataGridView and Windows. If a click removes the row, ignore clicks within the double-click time (SystemInformation.DoubleClickTime) yourself. GetSelectedRows()returns every row that has a selected cell inCellSelect. UseSelectionMode = RowHeaderSelectfor DataGridView's rule: only rows selected with the row header (orSelectRow, Ctrl+A, the top-left corner) count, and Delete key row deletion (DeleteKeyAction = DeleteRows) removes only those (nothing when no row is selected that way). Ctrl+A and the top-left corner select every row in this mode.CellValueChangedalso comes for values set by code, includingRows.Add(values)andCells(r, c).Value = ...(one event per cell,e.Reason = Code). DataGridView does not raise it forRows.Add. Skip them withIf e.Reason = NoxGridChangeReason.Code Then Return.CellValueChangedis not raised when the value is the same, ande.Reasontells why it changed (UserEdit,UserToggle,Paste,Undo,Redo,DeleteKey,Replace,Code). Code that saves to a database only on user changes can checke.Reasoninstead of a loading flag.- Paste, undo, find and Delete key clearing are on by default (see the table below). Turn them all off at once with
UserDataChanges = EditOnlywhen values must go through your own save path, or handleCellPasting. Replace (Ctrl+H) is off by default (AllowReplace). - Excel export writes only the shown rows by default (
NoxExportOptions.VisibleRowsOnly = True), so a filter on screen also filters the file. Set it to False to export every row, as a loop over DataGridView rows did. - The second press of a double-click raises
CellDoubleClickandCellMouseDoubleClick, notCellClickandCellMouseClickagain, as in DataGridView. A check box changes only once. - Columns are recreated when the data source changes. Set
KeepGeneratedColumnSettings = Trueto keep header text, widths and order, or adjust columns inDataBindingComplete. - Unbound columns in a bound grid follow the data item when the data is sorted or filtered, and also when the same items are bound again (DataGridView clears them when
DataSourceis set again). A list with different items starts empty. CallClearUnboundValues()to start empty yourself. - Some values are corrected quietly instead of throwing.
HorizontalScrollingOffsetset before the grid is shown becomes 0;FirstDisplayedRowIndexset to a hidden row moves to the nearest shown row (DataGridView throws). - A select-all check box is built in:
NoxGridCheckBoxColumn.HeaderCheckBox = True. - Read-only check boxes are grayed out. Set
ReadOnlyAppearance = Normalon the check box column to draw them like DataGridView does (they still cannot be changed).CheckedImageandUncheckedImagedraw pictures instead of check boxes.
Defaults that are on
These user features are on in a new grid. Turn off what a screen does not need, or use UserDataChanges = EditOnly to turn off every one that changes data.
| Property | Default | What the user can do |
|---|---|---|
AllowPaste |
True | paste with Ctrl+V and Shift+Insert |
AllowUndo |
True | undo and redo with Ctrl+Z, Ctrl+Y |
DeleteKeyAction |
ClearValues |
clear the selected cells with Delete |
AllowFind |
True | find with Ctrl+F and F3 (finding never changes data) |
AllowReplace |
False | replace with Ctrl+H |
AllowUserToResizeColumns |
True | resize columns (AllowUserToOrderColumns, dragging columns, is False) |
column SortMode |
Automatic |
sort by clicking the header (check box, combo box, button, image and progress columns: NotSortable, as in DataGridView) |
AllowUserToAddRows |
False | add rows from an empty last row |
AllowFiltering |
False | filter buttons in the headers |
Read-only list screens
A list where the user only looks, or only ticks a check box:
NoxGrid1.ReadOnly = True
NoxGrid1.UserDataChanges = NoxGridUserDataChanges.EditOnly ' no paste, undo, replace or Delete clearing
colPick.EditableWhenGridReadOnly = True ' only this check box column can be changed
To let the user select and copy an ID without changing it, and to stop a barcode scanner from typing into it:
colBarcode.ReadOnly = True
colBarcode.ReadOnlyMode = NoxGridReadOnlyMode.Selectable ' double-click opens a read-only edit box
colBarcode.EditTrigger = NoxGridEditTrigger.DoubleClickOnly ' typing and F2 do not open it
Sorting
- Only text, number, date and label columns sort by default, as in DataGridView. Check box, combo box, button, image and progress columns are
NotSortable; setSortMode = Automaticto sort one by its header.Sortcalled from code works whateverSortModeis. ClearSort()puts rows back in the order before sorting (unbound grid). Rows added while sorted go to the end in the order they were added, rows inserted at the top (Rows.Insert(0, ...)) go to the front, removed rows are gone.ClearSort(False)only removes the sort indicator. A bound grid goes back to the data source order (for aDataTable, its row order). Columns your code sorts itself (Programmatic) only lose the indicator.SortCycle = AscendingDescendingNonemakes the third header click do the same.- Equal values keep their current order, also in descending order.
- A
List(Of T)cannot be sorted, as in DataGridView: the header click does nothing andSortthrowsNotSupportedException.CanSort(column)tells you beforehand. Bind aDataTable, or sort in your code withSortMode = Programmatic. The grid will sort such lists itself (screen order only) in 1.1. - Text compares as text by default (
"10"before"2", empty cells first in ascending order). Set the column'sSortCompareMode = Naturalto compare numbers inside text as numbers (2 < 10,1:80 < 1:1280,9h < 13h; leading zeros are ignored), and the grid'sEmptyCellsLast = Trueto put empty cells (Nothing,DBNull,"") last in both directions, as in Excel. SortCompareworks as in DataGridView (unbound grid): sete.SortResultande.Handled = True. Return the result for ascending order; the grid reverses it for a descending sort. Return 0 for equal values to keep their order.e.SortOrdertells the direction, so a handler that keeps empty cells last reverses its empty-cell result when sorting descending:
Private Sub NoxGrid1_SortCompare(sender As Object, e As NoxGridSortCompareEventArgs) Handles NoxGrid1.SortCompare
Dim empty1 = String.IsNullOrEmpty(TryCast(e.CellValue1, String))
Dim empty2 = String.IsNullOrEmpty(TryCast(e.CellValue2, String))
If empty1 OrElse empty2 Then
Dim r = If(empty1 = empty2, 0, If(empty1, 1, -1)) ' empty cells last
e.SortResult = If(e.SortOrder = NoxSortOrder.Descending, -r, r) ' the grid reverses descending results
Else
e.SortResult = NaturalCompare(CStr(e.CellValue1), CStr(e.CellValue2))
If e.SortResult = 0 Then e.SortResult = CInt(NoxGrid1(e.RowIndex1, "Seq")).CompareTo(CInt(NoxGrid1(e.RowIndex2, "Seq")))
End If
e.Handled = True
End Sub
EmptyCellsLast applies only to the grid's own comparison; with Handled = True your result decides, empty cells included.
Guaranteed behavior
- Combo boxes with
LimitToList = False: the committed value is the text in the edit box, including text typed after picking an item.CaretToEndOnSelect = Trueputs the caret at the end after picking. - Excel export keeps text as text. String values are written as text cells, so registration numbers with leading zeros,
1:80or09-03never turn into numbers or dates. - Typing Korean (or other IME input) into a selected cell opens the edit box when composition starts, so the first syllable is not lost or split.
- F4 and Alt+Down open a combo cell's list, as in DataGridView.
EndEdit()returns False and keeps editing whenCellValidatingsetsCancel, the text cannot be converted to the column's type, a typed formula is invalid, a validation rule fails (Required,MinimumValue,MaximumValue,AllowedValues,MaxLength,ValidationPattern) or the data source refuses the value (for example a constraint of aDataTable). The last four are also reported throughDataError.- Column names are kept by the designer. A column's
Nameis its designer name ((Name)in the Properties window) and is saved in the form's designer code, whatever itsDataPropertyNameis. - No selection events while the grid is being disposed.
SelectionChanged,CurrentCellChangedandCurrentRowChangedare not raised onceDisposestarts, so closing a form does not run your handlers against controls that are already gone. - App event handlers called while painting (
CellFormatting,CellPainting,ColumnHeaderPainting,CellToolTipTextNeeded,FooterValueNeeded) cannot break the grid: an exception keeps the default look for that cell and is reported throughDataError.
Visual Studio designer
The NoxGrid designer window, the smart tag and the column editor come from Nox.Grid.Design.dll (included in the NuGet package). Without it, a form with a NoxGrid still opens and draws in the designer and the Properties window works, but adding and editing columns in the designer is not supported. The app itself never needs Nox.Grid.Design.dll.
Threads
Like DataGridView, NoxGrid must be used from the UI thread that created it. From another thread (device input, timers, polling), switch first:
If NoxGrid1.InvokeRequired Then
NoxGrid1.BeginInvoke(Sub() NoxGrid1.Rows.Add(code, value))
Else
NoxGrid1.Rows.Add(code, value)
End If
Binding: change the bound DataTable or BindingList on the UI thread too; the grid listens to its change events.