How to: Initialize Cells in Newly Created Rows
- 2 minutes to read
The following example demonstrates how to handle the ColumnView.InitNewRow event to initialize the “ID” and “CreateDate” fields (cells) of a new data row.
using System;
using System.Data;
using DevExpress.XtraGrid.Views.Grid;
namespace DXApplication9 {
public partial class Form1 : DevExpress.XtraEditors.XtraForm {
public Form1() {
InitializeComponent();
gridControl1.DataSource = InitDataTable();
Load += Form1_Load;
buttonAddNewOrder.Click += ButtonAddNewOrder_Click;
gridView1.InitNewRow += GridView1_InitNewRow;
// Displays the New Item Row within the Grid View.
gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;
}
private void ButtonAddNewOrder_Click(object sender, EventArgs e) {
// Adds a new record to the grid's data source.
gridView1.AddNewRow();
}
private void GridView1_InitNewRow(object sender, InitNewRowEventArgs e) {
GridView view = sender as GridView;
view.SetRowCellValue(e.RowHandle, view.Columns["ID"], Guid.NewGuid());
view.SetRowCellValue(e.RowHandle, view.Columns["CreateDate"], DateTime.Now);
}
private void Form1_Load(object sender, EventArgs e) {
// Makes the ID column read-only. Users cannnot edit its values.
gridView1.Columns["ID"].OptionsColumn.ReadOnly = true;
}
DataTable InitDataTable() {
DataTable table = new DataTable("DataRecords");
table.Columns.AddRange(new DataColumn[] {
new DataColumn("ID", typeof(Guid)),
new DataColumn("CreateDate", typeof(DateTime)),
new DataColumn("Customer Name", typeof(string))
});
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2024, 1, 1, 9, 44, 12), "Silva" });
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2023, 12, 31, 11, 15, 18), "Mike" });
table.Rows.Add(new object[] { Guid.NewGuid(), new DateTime(2023, 12, 31, 10, 20, 10), "Nathan" });
return table;
}
}
}