Pages

Monday, January 13, 2014

Create new rows in a DataGrid control using the DataGridItem object (ASP.NET)

Did you know that .NET allows you to add new rows to the DataGrid that match your DataGrid's current styles? To do this, you just need to create new DataGridItem objects. The syntax for creating these objects is as follows:

New DataGridItem(itemIndex, dataSetIndex, itemType)

The itemIndex is the index of the item in the DataGrid control and the dataSetIndex is the index number of the bound data source item that appears in the DataGrid. When adding new rows, these values aren't relevant and you can use 0 for both of them. The itemType argument is important because it identifies the type of DataGridItem object you want. Valid values include: Item, Header, and Footer to name a few. Following is an example of how you'll create a new DataGridItem header:

Dim dgItem As DataGridItem
dgItem = New DataGridItem(0, 0, ListItemType.Header)


This line of code creates a DataGrid Header in whichever style you've defined for DataGrid headers. Next, you need to add data to the DataGridItem object. You do this by adding new cells to the DataGridItem object. The next set of code creates two columns and adds them to the header:

Dim dgCell As TableCell

dgCell = New TableCell
dgCell.Text = "Title"
dgItem.Cells.Add(dgCell)

dgCell = New TableCell
dgCell.Text = "Author"
dgItem.Cells.Add(dgCell)


All that's left to do is add the DataGridItem object to the DataGrid rows collection. For this task you have the Add or AddAt methods of the controls collection. The Add method adds the row to the end of the collection and AddAt adds the row to an existing location in the collection. The following line of code adds the new header to the end of a DataGrid named DataGrid1:

DataGrid1.Controls(0).Controls.Add(dgItem)


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.