Click here to Skip to main content
15,890,282 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to duplicate a highlighted row in a databound datagridview. The code works for the most part. The flaw issue is that when it pastes the new row it moves it over two columns in the row. Not sure why or where to even look to find an answer to this as I've never seen anything like it.

What I have tried:

VB
Dim CopyRowIndex = OpeningsDataGridView1.CurrentRow.Index
               Dim dt As New DataTable
               dt = OpeningsDataGridView1.DataSource
               dt.Rows.Add(OpeningsDataGridView1.Rows(CopyRowIndex).Cells.Cast(Of DataGridViewCell).Select(Function(c) c.Value).ToArray)
Posted
Updated 7-Nov-19 23:47pm
v2
Comments
Kornfeld Eliyahu Peter 29-Oct-19 10:55am    
Are you talking about a visual issue here?
Can you explain more what do you mean by 'moves it over two columns in the row'?
Member 11672076 29-Oct-19 11:08am    
I'm trying to figure out how to add pictures but yes it's visual. Column one row one has a value of 3 in it. When it is copied it shows up in column 3 row 2. The row is correct but the column is not.

1 solution

Well...

In case when a DataGridView[^] control is bound with datatable, you can't create a copy of DataGridViewRow[^] object.

MSDN documentation states:
Remarks

You can use the Rows collection to manually populate a DataGridView control instead of binding it to a data source.


See: DataGridView.Rows[^]


Conclusion: you have to add a "row" (record) to your datatable!
Steps to do:
1) get selected DataGridViewRow and read the value of cell which is unique
2) find that unique value in a datatable
3) add a copy of DataRow[^] to the DataTable object

VB.NET
'get datatable
Dim dt As DataTable = DirectCast(dgv.DataSource, DataTable)
Dim ValueToFind = ... 'your logic here
'find unique value
Dim rowToCopy = dt.AsEnumerable() _
	.Where(Function(x) x.Field(Of Integer)("FieldName") = ValueToFind) _
	.FirstOrDefault()
'create new row
Dim nr = dt.NewRow()
'copy data
nr.ItemArray = rowToCopy.ItemArray
'add new row
dt.Rows.Add(nr)
're-bind datasource
dgv.DataSource = dt


Note: An exact copy of DataRow is not allowed in case of primary key violation.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900