Question Property 'item' is read only?

cayongrayoo

Member
Joined
Feb 8, 2012
Messages
9
Programming Experience
Beginner
Hi i'm trying to move a row from a datagridview(caches) to another datagridview(chosen). The user clicks a button on the row he/she wants and it moves to the other datagridview(chosen).
The first datagridview(caches) uses a dataset as its data source.
So far my program clones the row of which the button is pressed, into a datagridviewrow(row).
It then adds the columns from the first datagridview(caches) to the new datagridview(chosen).
But when I try and put the cloned row into the first row I get: Property 'item' is read only.
Here is my code:

Private Sub cacheList_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cacheList.Click caches.Visible = True
caches.DataSource = Ds.Tables(3)
Dim btn As New DataGridViewButtonColumn()
caches.Columns.Add(btn)
btn.HeaderText = "Click Data"
btn.Text = "Click Here"
btn.Name = "btn"
btn.UseColumnTextForButtonValue = True
End Sub
Private Sub DataGridView1_CellClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles caches.CellClick
Dim row As DataGridViewRow
chosen.ColumnCount = 15
chosen.Columns(0).Name = caches.Columns(0).Name
If e.RowIndex = 3 Then
row = caches.Rows(3).Clone
chosen.Rows(0) = row
End If

Any help is massively appreciated.
 
Property 'item' is read only?
refers to this code:
VB.NET:
chosen.Rows(0) = row
which is short for accessing default property Item:
VB.NET:
chosen.Rows.[B][U]Item[/U][/B](0) = row
Rows property returns a DataGridViewRowCollection object, and its Item property is readonly, you can get a DataGridViewRow object, but you can't set one. To add a row to the collection use one of the methods that does that, for example one of the Add methods.

Your first DataGridView is data bound however, so cloning a DataGridViewRow leaves you with an empty row. When data bound the grid control itself holds no data, it just displays it. So to copy data from a bound row to a new row in an unbound DataGridView you have to get hold of the data and copy that. To do this first get the rows DataBoundItem, which is a DataRowView (a view of a DataRow), then for example get the ItemArray of the DataRow. This example uses one of the Add methods mention above that takes an array of values that should fill the new row:
Dim data As DataRowView = CType(Me.DataGridView1.Rows(e.RowIndex).DataBoundItem, DataRowView)
Me.DataGridView2.Rows.Add(data.Row.ItemArray)
 
Ahh I see.
That actually makes a lot of sense after reading that.
And it worked :D
Thanks very much JohnH!!!!
Just realized datagridviewrow has a select row function so I dont even need the button... haha oh well.
Cheers again!!
 
Back
Top