Auto Generated Columns
2 Mar 20223 minutes to read
The Columns
are automatically generated when Columns
declaration is empty or undefined while initializing the grid. All the columns in the DataSource
are bound as grid columns.
@Html.EJS().Grid("Auto").DataSource((IEnumerable<object>)ViewBag.dataSource).Render()
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
When columns are auto-generated, the column
Type
will be determined from the first record of theDataSource
.
Set Primary key column for auto generated columns when editing is enabled
Primary key can be defined in the declaration of column object of the grid. When you did not declare the columns, the grid will generate the columns automatically. For these auto generated columns, you can set IsPrimaryKey
column property as true by using the following ways,
If Primary key “column index” is known then refer the following example
@Html.EJS().Grid("Auto").DataSource((IEnumerable<object>)ViewBag.dataSource).DataBound("dataBound").EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true); }).Render()
<script>
function dataBound() {
var grid = document.getElementById('Auto').ej2_instances[0];
var column = grid.columns[0];
column.isPrimaryKey = 'true';
}
</script>
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}
If Primary key “column fieldname” is known then you can get the column by using var column = grid.getColumnByField(‘OrderID’) and then set primary key by defining Column.IsPrimaryKey = ‘true’
Set column options to auto generated columns
You can set column options such as Format
, Width
to the auto generated columns by using DataBound
event of the grid.
In the below example, Width
is set for OrderID column, date type is set for OrderDate column and numeric type is set for Freight column.
@Html.EJS().Grid("Auto").DataSource((IEnumerable<object>)ViewBag.dataSource).DataBound("dataBound").Render()
<script>
function dataBound() {
for (var i = 0; i < this.columns.length; i++) {
this.columns[0].width = 120;
if (this.columns[i].field === "OrderDate") {
this.columns[i].type = "date";
}
if (this.columns[i].type === "date") {
this.columns[i].format = { type: "date", format: "dd/MM/yyyy" };
}
this.columns[3].format = "P2";
}
this.refreshColumns();
}
</script>
public IActionResult Index()
{
var Order = OrderDetails.GetAllRecords();
ViewBag.DataSource = Order;
return View();
}