我正在尝试将DataGridViewRow的精确副本存储到同一行的标记中,一切正常,结果如其应有的一样……除了,当我尝试使用Name列(在代码的最后一行),它告诉我列名不存在。但是,如果我使用索引,一切都会很好。
我尝试使用方法CreateCells()或Clone()原始表的结构,但仍然无法正常工作。
我可以坚持使用索引。但是我更希望通过列名获取值。有可能吗?
''Create and populate a datagridview with one row
Dim DGV As New DataGridView
DGV.Columns.Add("No1", "No1")
DGV.Columns.Add("No2", "No2")
DGV.Columns.Add("No3", "No3")
Dim Objects As New List(Of Object)
Objects.Add("1")
Objects.Add("2")
Objects.Add("3")
DGV.Rows.Add(Objects.ToArray)
'' Loop to store a copy of itself into the Row's Tag
For Each selectedrows As DataGridViewRow In DGV.Rows
Dim DataGridViewRow As New DataGridViewRow
Dim CellArray As New List(Of Object)
DataGridViewRow.CreateCells(DGV) ''I have tried DataGridViewRow = selectedrow.clone and it still doesnt work
For Each Cell As DataGridViewCell In selectedrows.Cells
CellArray.Add(Cell.Value)
Next
DataGridViewRow.SetValues(CellArray.ToArray)
selectedrows.Tag = DataGridViewRow
Next
DGV.Rows(0).Cells(0).Value = "Change"
MessageBox.Show(DGV.Rows(0).Cells(0).Value) ''Works (Output: Change)
MessageBox.Show(DGV.Rows(0).Tag.Cells(0).Value) ''Works (Output: 1)
MessageBox.Show(DGV.Rows(0).Cells("No1").Value) ''Works (Output: Change)
MessageBox.Show(DGV.Rows(0).Tag.Cells("No1").Value) ''Doesnt Work (Output: System.ArgumentException: 'Column named No1 cannot be found.
参数名称:columnName')
答案 0 :(得分:0)
如果您尝试更改行呢?
Dim rwIdx = 0
For Each selectedrows As DataGridViewRow In DGV.Rows
Dim myDataGridViewRow As New DataGridViewRow
myDataGridViewRow = DGV.Rows(rwIdx)
rwIdx = rwIdx + 1
selectedrows.Tag = myDataGridViewRow
Next
以上仅指同一行,不克隆数据,下面,我将选定的行复制到另一个datagridview:
Dim DGV As New DataGridView
DGV.Columns.Add("No1", "No1")
DGV.Columns.Add("No2", "No2")
DGV.Columns.Add("No3", "No3")
Dim Objects As New List(Of Object)
Objects.Add("1")
Objects.Add("2")
Objects.Add("3")
DGV.Rows.Add(Objects.ToArray)
'' Loop to store a copy of itself into the Row's Tag
Dim DataGridViewRow As New DataGridViewRow
Dim myRowIdx As Integer = 0
For Each selectedrows As DataGridViewRow In DGV.Rows
DataGridViewRow = New DataGridViewRow
Dim dgv2 As New DataGridView
For Each col As DataGridViewColumn In DGV.Columns
dgv2.Columns.Add(DirectCast(col.Clone, DataGridViewColumn))
Next
For Each Cell As DataGridViewCell In selectedrows.Cells
dgv2.Rows(0).Cells(Cell.ColumnIndex).Value = Cell.Value
Next
selectedrows.Tag = dgv2.Rows(0)
Next
MessageBox.Show(DGV.Rows(0).Cells(0).Value.ToString) ''Works (Output: 1)
MessageBox.Show(DirectCast(DGV.Rows(0).Tag, DataGridViewRow).Cells(0).Value.ToString) ''Works (Output: 1)
DGV.Rows(0).Cells(0).Value = "Change"
MessageBox.Show(DGV.Rows(0).Cells(0).Value.ToString) ''Works (Output: Change)
MessageBox.Show(DirectCast(DGV.Rows(0).Tag, DataGridViewRow).Cells(0).Value.ToString) ''Works (Output: 1)
MessageBox.Show(DGV.Rows(0).Cells("No1").Value.ToString) ''Works (Output: Change)
MessageBox.Show(DirectCast(DGV.Rows(0).Tag, DataGridViewRow).Cells("No1").Value.ToString) ''Works (Output: 1)