|
-
Oct 16th, 2008, 02:54 PM
#1
Thread Starter
Hyperactive Member
[2008] DataGridView and adding Rows
I'm having a problem adding rows to a datagridview. I'm sure its just a stupid oversight on my part, but I just can't figure what.
So, I have a datagridview with allowusertoaddrows = false and autogeneratecolumns = false and some columns defined (as in following example). I create a new datagridviewrow and add it to the datagridview and it picks up the cells just fine, but it has a rowindex of -1. So when I try to set the value of one of the cells in the row, i get an error, objectoutofrangeexception, because the rowindex is -1.
How do I create a row and set the values in the row after adding it to the datagridview? Here is some code to replicate the problem.
I've replicated my problem with the following code (just add a datagridview to a new windows form project):
Code:
Dim newCollection As New List(Of Long)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.InitializeDataGridView1()
Me.AddSomeItemsToList()
Me.AddSomeRows()
End Sub
Friend Sub AddSomeItemsToList()
For i As Integer = 1 To 5
Me.newCollection.Add(i)
Next
End Sub
Friend Sub AddSomeRows()
Try
For Each item As Long In Me.newCollection
Dim newRow As New DataGridViewRow
Me.DataGridView1.Rows.Add(newRow)
newRow.Cells("clmTest").Value = CLng(item)
Next
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Friend Sub InitializeDataGridView1()
With Me.DataGridView1
.AutoGenerateColumns = False
.AllowUserToAddRows = False
If Not .Columns.Contains("clmTest") Then
Dim clmTest As New DataGridViewTextBoxColumn
With clmTest
.ValueType = GetType(Long)
.ReadOnly = True
.Width = 100
.DisplayIndex = 0
.HeaderText = "Test"
.Name = "clmTest"
End With
.Columns.Add(clmTest)
End If
End With
End Sub
Thanks,
Jerome
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|