Skip to main content

Add and Remove Rows

  • 8 minutes to read

Common Requirements

The Data Grid uses methods of the data source assigned to the DataSource property to add and remove rows. You and your users can add and remove Data Grid rows only if your data source has such API. For example, the ExcelDataSource is a read-only data source, so data in a grid bound to this source cannot be edited. Similarly, if a Data Grid is bound to a data source that implements the IBindingList interface, the availability of row operations depends on the Boolean AllowNew and AllowRemove settings. Note that Lists with simple type objects (for example, List<string>) are not supported. Instead, you need to create a class with one property of this required simple type. This class must have an empty default constructor.

New Item Row

The Data Grid can display an empty row that enables users to add new records. This row is identified by an asterisk (*) displayed within a corresponding row indicator cell. To cancel the addition of a new row, users can press Esc.

Data Grid - New Item Row

You cannot obtain or modify cell values until there is a row object that corresponds to a record. If the New Item Row is used to add new rows, Data Grid initializes a new row object only after a user modifies any cell within the New Item Row.

Do not manually add or remove rows before a new row object is posted into an underlying Grid data source. The Data Grid posts new row objects when the New Item Row loses focus, or when the UpdateCurrentRow method is called.

Demos: Table View | Use New Item Row to add rows

Related API

Initialize New Rows

The ColumnView.InitNewRow event fires whenever a user adds a new record. Handle this event and call corresponding SetValue and GetValue methods to facilitate user input and auto-fill new row cells with default values.

In the Init newly added rows in a custom manner demo module, every new row automatically receives initial values for cells under the “Record Date”, “Name”, and “Notes” columns.

 gridView.OptionsView.NewItemRowPosition = NewItemRowPosition.Top;

 // Handle the InitNewRow event to initialize newly added rows. To initialize row cells, use the SetRowCellValue method.
 gridView.InitNewRow += (s, e) => {
     GridView view = s as GridView;
     // Set the new row cell value.
     view.SetRowCellValue(e.RowHandle, view.Columns["RecordDate"], DateTime.Today);
     view.SetRowCellValue(e.RowHandle, view.Columns["Name"], "CustomName");
     // Obtain the new row cell value.
     int newRowID = Convert.ToInt32(view.GetRowCellValue(e.RowHandle, "ID"));
     view.SetRowCellValue(e.RowHandle, view.Columns["Notes"], string.Format("Row ID: {0}",newRowID));
 };

Data Navigator

The Data Navigator is an embedded toolbar that allows users to navigate through Data Grid records and add/remove rows.

Data Grid - Data Navigator

Related API

External Control Navigator

The Data Navigator is a ControlNavigator object displayed directly within a Data Grid. If needed, you can create a standalone Control Navigator and position it anywhere outside the Grid. Utilize the navigator’s ControlNavigator.NavigatableControl property to bind the navigator to a Data Grid. The Control Navigator can also navigate through records of the Tree List and Vertical Grid controls.

Data Grid - External Control Navigator

Add and Remove Rows in Code

  • Modify the underlying data source

    If your data source allows users to add and remove records, you can use a data source API to modify Grid rows. If a data source does not implement the IBindingList interface, it does not send add/remove notifications to the Data Grid. In this case, call the GridControl.RefreshDataSource method (which updates the main Grid view) or the BaseView.RefreshData method (which updates this specific view) to update the Data Grid manually. The GridOptionsNavigation.AutoFocusNewRow property allows the Data Grid to automatically focus new records added to a data source.

    The code below adds a new record to a BindingList<T> object that serves as a data source for a Data Grid. Since this data source supports update notifications, you don’t need to refresh the Data Grid manually.

    private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e) {
        (gridControl1.DataSource as BindingList<SalesPerson>).AddNew();
    }
    
  • ColumnView.AddNewRow

    Adds a blank row to the Data Grid. If the New Item Row is enabled, this method moves focus to this element. Otherwise, the new record is temporarily placed below the existing records. After a user enters cell values and the row is accepted, the new row moves to its final location according to the current Data Group’s filter, group, and sort settings. To accept a new row manually, call the ColumnView.UpdateCurrentRow method from code. The following code shows how to add a new row to a data group. It is assumed that data within a Grid View is grouped against one or more columns. The row is added to the same group as the currently focused row.

    private void AddNewRowInGroupMode(DevExpress.XtraGrid.Views.Grid.GridView View) {
        //Get the handle of the source data row 
        //The row provides group column values for a new row 
        int rowHandle = View.GetDataRowHandleByGroupRowHandle(View.FocusedRowHandle);
        //Store group column values 
        object [] groupValues = null;
        int groupColumnCount = View.GroupedColumns.Count;
        if(groupColumnCount > 0) {
            groupValues = new object[groupColumnCount];
            for(int i = 0; i < groupColumnCount; i++) {
                groupValues[i] = View.GetRowCellValue(rowHandle, View.GroupedColumns[i]);
            }
        }
        //Add a new row 
        View.AddNewRow();
        //Get the handle of the new row 
        int newRowHandle = View.FocusedRowHandle;
        object newRow = View.GetRow(newRowHandle);
        //Set cell values corresponding to group columns 
        if(groupColumnCount > 0) {                
            for(int i = 0; i < groupColumnCount; i++) {
                View.SetRowCellValue(newRowHandle, View.GroupedColumns[i], groupValues[i]);
            }
        }
        //Accept the new row 
        //The row moves to a new position according to the current group settings 
        View.UpdateCurrentRow();
        //Locate the new row 
        for(int n = 0; n < View.DataRowCount; n++) {
            if(View.GetRow(n).Equals(newRow)) {
                View.FocusedRowHandle = n;
                break;
            }
        }
    }
    
  • ColumnView.DeleteRow

    Removes a data record or a group row from the View. If a data source contains multiple tables with master-detail relationships, this method removes a row together with its associated child rows. The code snippet below illustrates how to remove the focused row when a user presses the Ctrl+Del shortcut.

    private void gridView1_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e) {
            if (e.KeyCode == Keys.Delete && e.Modifiers == Keys.Control) {
                if (MessageBox.Show("Delete row?", "Confirmation", MessageBoxButtons.YesNo) != 
                  DialogResult.Yes)
                    return;
                GridView view = sender as GridView;                
                view.DeleteRow(view.FocusedRowHandle);
            }
        }
    
  • ColumnView.DeleteSelectedRows

    If the ColumnViewOptionsSelection.MultiSelect property is enabled, users can select multiple Data Grid rows (or row cells, depending on the current GridOptionsSelection.MultiSelectMode setting). The DeleteSelectedRows() method removes all selected rows and all rows with selected cells if individual cell selection is enabled.

Demos: Remove rows with the Ctrl+Delete shortcut | Prevent a row from being deleted

How to Save a Modified Row

Data Grid and other DevExpress data-aware controls (Gantt Control, Vertical Grid, TreeList, etc.) do not interact with real data storages. Instead, they use data sources connected to these storages. Data-aware controls save user edits to data sources, but you need to manually post these changes to underlying storages. See this help topic for more information: Post Data to an Underlying Data Source.

To post modified row values to an underlying source, handle the ColumnView.RowUpdated event. This event fires when a user navigates away from the edited row.

DXApplication.AdventureWorksDW2008R2Entities dbContext;

void gridView1_RowUpdated(object sender, RowObjectEventArgs e) {
    dbContext.SaveChanges();
}

Note that RowUpdated does not fire while there is an active editor (the BaseView.IsEditing property returns true). To trigger this event manually, call the BaseView.CloseEditor method to close the editor, and then call the BaseView.UpdateCurrentRow method.

Cheat Sheets and Best Practices

DevExpress WinForms UI controls introduce almost the same API to add, remove, and initialize rows. Read the following quick-reference guides for detailed information:

Add, Remove, and Initialize Rows