Reputation: 1
I am a newbie then a self taught only, I have a datagridview that will load the data from my database and it has a hidden column I want to export a selected row of data into excel but what I want to export is the only visible column in my datagridview to excel and the selected row only
I don't know how to do this right!
How can I combine this? the selected column and only visible column will be exported in my excel
For i = 0 To SelectedRowCount - 1 currentVisibleColumn = columnCollection.GetFirstColumn(DataGridViewElementStates.Visible) lastColumnExported = currentVisibleColumn For j = 1 To visibleColumnCount + 1 Dim value = DataGridView1.Rows(i).Cells(currentVisibleColumn.Index).Value If value IsNot vbNullString Then xlWorkSheet.Cells(i + 2, j) = value.ToString() xlWorkSheet.Cells(i + 2, j + 1) = DataGridView1(j, DataGridView1.SelectedRows(i).Index).Value.ToString() End If currentVisibleColumn = columnCollection.GetNextColumn(lastColumnExported, DataGridViewElementStates.Visible, DataGridViewElementStates.None) lastColumnExported = currentVisibleColumn Next Next
when I do this it gives me "'Object reference not set to an instance of an object.'"
Upvotes: 0
Views: 309
Reputation: 54477
Your code should be more like this:
Dim columns = (From column In DataGridView1.Columns.Cast(Of DataGridViewColumn)()
Where column.Visible
Order By column.DisplayIndex).ToArray()
For Each row As DataGridViewRow In DataGridView1.SelectedRows
For Each column In columns
Dim value = row.Cells(column.Index)
If value IsNot Nothing Then
'...
End If
Next
Next
If you still get a NullReferenceException
with that code then you'll need to be more specific about it to get more help but the solution to such issues is almost always the same.
Upvotes: 0