Adding
DataGrid Item to a DataGrid without DataSource
In lots of places it is required to add datagrid item(row) to DataGrid. Easiest
way to do this is to add one row to DataSource and then bind the DataGrid with
the new DataSource. This way new datagrid item will be added to DataGrid.
This method is fine, if DataGrid is binded with DataSource. But in many
cases we might not have DataSource for just adding one row to DataGrid. In that
case we need to add DataItem directly to DataGrid. In this code snippet we are
going to see how to do this,
Here
is the code snippet that is required to add datagrid item to datagrid without
datasource,
Dim dgItem As
DataGridItem
Dim dgCell As
TableCell
Dim intColCounter As Int16
dgItem =
New DataGridItem(2, 0,
ListItemType.Item)
For intColCounter = 0 To DataGrid1.Columns.Count - 1
dgCell = New TableCell
dgItem.Cells.Add(dgCell)
dgcell.Text = "Value for the column"
Next
DataGrid1.Controls(0).Controls.AddAt(2
+ 2, dgItem)
First thing is, we need to create DataGridItem. Datagrid item constructor
accepts three parameters,
-
itemIndex:
The index of the item in the DataGrid control from the Items collection.
-
dataSetIndex:
The index number of the item, from the bound data source, that appears in the
DataGrid control.
-
itemType: One of the ListItemType values.
Then in that datagrid item, we need to create columns(cells) based on column
collection in DataGrid. While adding cells, we can set the default value
for cell. Now datagrid item is ready, we need to add it to DataGrid. For
adding datagrid item, we need to use control collection of Datagrid. Control
collection is having a method called "AddAt" with which you can add the
datagrid item at any place inside grid. In this example, i have added at 2nd
position. It will come as second row in datagrid.
|