Why is my GridViewRow.DataItemIndex incorrect and DataItem null?
I'm trying to immediately set a row to Edit mode after it is created. However, my GridViewRow has an incorrect DataItemIndex and a null DataItem...
Here's a general idea of what my code is doing: (pseudo VB code)
Protected Sub gvItems_RowCommand(....)
if (e.CommandName = 'New')
Begin
// create new empty and add it to my data table
m_dtItems.Rows.Add(m_dtItems.NewRow()) // m_dtItems is a DataTable
// rebind the gridview to the modified data table
gvItems.DataSource = m_dtItems
gvItems.DataBind()
// loop through grid view to find the row we just inserted
Dim newRowDataItemIndex As Integer = m_dtItems.Rows.IndexOf(dRow)
For each row in gvItems.Rows
if (row.DataItemIndex = newRowDataItemIndex)
gvItems.EditIndex = row.RowIndex
// rebind the grid so the edit index takes e开发者_JAVA百科ffect
gvItems.DataSource = m_dtItems
gvItems.DataBind()
End
End Sub
The problem is that GridViewRow.DataItemIndex is not correct. It seems to be equal to the RowIndex. Also, my GridViewRow.DataItem is null except inside GridViewRow_RowDataBound event.
I'm not using paging or sorting either which I know causes problems.
What am I doing wrong?
It looks like the problem was that a data table can contain deleted rows (eg. DataRow.RowState = Deleted) and the grid view only contains "valid" rows. Therefore, the DataItemIndexes do not match and you can also get exceptions if you try to refer to a deleted row.
The solution was to bind the grid view to a data view (myDataTable.DefaultView) with a RowStateFilter of CurrentRowsOnly and then do all changes (add, edit, and deletions) through the data view.
精彩评论