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:

  • CellBeginEdit has e.StartReason (Keystroke, F2, DropDownKey, DoubleClick, Click, Enter, Code) and e.IsReadOnlyEdit.
  • Binding different data clears the filters. Changing DataSource or DataMember clears the header filters, as it clears the sort, and raises FilterChanged. Rows added or changed in the same data keep the filters.
  • Finding columns by name: grid(r, "name"), row("name") and Cells(r, "name") look up the column Name first, then DataPropertyName.
  • Filtered-out rows stay in Rows. Filtering only hides rows on screen; it does not change the bound DataTable or DataView RowFilter. Rows.Count and For Each include every row; row.FilteredOut, row.Displayed and VisibleRowCount tell what is shown. To save regardless of the filter, read the bound DataTable.
  • 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's DroppedRowCount; with PasteAddsRows = True (unbound) the missing rows are added (same undo step, defaults from DefaultValuesNeeded). A cell that breaks a bound DataTable constraint is reverted, DataError is 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 (UserEdit here) and e.IsNested = True. Skip it with If 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 with IsNested = True.
  • ColumnHeaderMouseClick comes for the right button too (to show your own menu). Only the left button sorts.
  • DataError: e.Column is always set. e.RowIndex is -1 when the error comes from a header (ColumnHeaderPainting, a header tooltip) or the footer row (FooterValueNeeded).
  • CellFormatting can change the text, colors and bold (FormattedValue, BackColor, ForeColor, Bold, selection colors). For a different font or alignment use the column's Font and Alignment or the cell's style.

What works differently

  • No first row is selected after binding. Set SelectFirstRowOnBind = True for master-detail screens. It also works when only BindingSource.DataSource is 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, IsRemoved is True and using it throws.
  • Check boxes commit at once. Remove CellContentClick toggling, CommitEdit and CurrentCellDirtyStateChanged code, or the value changes twice. Keep CellContentClick for 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 = True to toggle it as DataGridView does. CellContentClick comes 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 in CellSelect. Use SelectionMode = RowHeaderSelect for DataGridView's rule: only rows selected with the row header (or SelectRow, 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.
  • CellValueChanged also comes for values set by code, including Rows.Add(values) and Cells(r, c).Value = ... (one event per cell, e.Reason = Code). DataGridView does not raise it for Rows.Add. Skip them with If e.Reason = NoxGridChangeReason.Code Then Return.
  • CellValueChanged is not raised when the value is the same, and e.Reason tells why it changed (UserEdit, UserToggle, Paste, Undo, Redo, DeleteKey, Replace, Code). Code that saves to a database only on user changes can check e.Reason instead 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 = EditOnly when values must go through your own save path, or handle CellPasting. 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 CellDoubleClick and CellMouseDoubleClick, not CellClick and CellMouseClick again, as in DataGridView. A check box changes only once.
  • Columns are recreated when the data source changes. Set KeepGeneratedColumnSettings = True to keep header text, widths and order, or adjust columns in DataBindingComplete.
  • 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 DataSource is set again). A list with different items starts empty. Call ClearUnboundValues() to start empty yourself.
  • Some values are corrected quietly instead of throwing. HorizontalScrollingOffset set before the grid is shown becomes 0; FirstDisplayedRowIndex set 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 = Normal on the check box column to draw them like DataGridView does (they still cannot be changed). CheckedImage and UncheckedImage draw 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; set SortMode = Automatic to sort one by its header. Sort called from code works whatever SortMode is.
  • 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 a DataTable, its row order). Columns your code sorts itself (Programmatic) only lose the indicator. SortCycle = AscendingDescendingNone makes 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 and Sort throws NotSupportedException. CanSort(column) tells you beforehand. Bind a DataTable, or sort in your code with SortMode = 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's SortCompareMode = Natural to compare numbers inside text as numbers (2 < 10, 1:80 < 1:1280, 9h < 13h; leading zeros are ignored), and the grid's EmptyCellsLast = True to put empty cells (Nothing, DBNull, "") last in both directions, as in Excel.
  • SortCompare works as in DataGridView (unbound grid): set e.SortResult and e.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.SortOrder tells 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 = True puts 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:80 or 09-03 never 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 when CellValidating sets Cancel, 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 a DataTable). The last four are also reported through DataError.
  • Column names are kept by the designer. A column's Name is its designer name ((Name) in the Properties window) and is saved in the form's designer code, whatever its DataPropertyName is.
  • No selection events while the grid is being disposed. SelectionChanged, CurrentCellChanged and CurrentRowChanged are not raised once Dispose starts, 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 through DataError.

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.