Solution: Datagridview Displays Only The Last Row

I have come across one problem where my DataGridView is only displaying the last record. I was surprised to see this because there are 30 rows in the table which all are needed to display in DataGridView after querying.

After lots of research on the internet, I found that I am not the only victim of this situation.(:D).

Below is my code which I had used before.

  1. Dim sadapt As New OleDbDataAdapter("SELECT * FROM [OrderDetail],[Order] WHERE [Order].Transaction=[OrderDetail].Transaction AND OrderNo='" & cboOrderNo.Text & "'", con)  
  2. Dim ds As DataSet = New DataSet  
  3. Dim trans As String = ""  
  4. sadapt.Fill(ds)  
  5. dgvDetails.Rows.Clear()  
  6. dgvDetails.RowCount = 1  
  7. For intRow = 0 To ds.Tables(0).Rows.Count - 1  
  8. dgvDetails.Rows(intRow).Cells("SrNo").Value = ds.Tables(0).Rows(intRow).Item("SrNo").ToString  
  9. dgvDetails.Rows(intRow).Cells("Particular").Value = ds.Tables(0).Rows(intRow).Item("Particular").ToString  
  10. dgvDetails.Rows(intRow).Cells("Barcode").Value = ds.Tables(0).Rows(intRow).Item("PlainTees").ToString  
  11. dgvDetails.RowCount = dgvDetails.RowCount + 1  
 ... where con is my connection.

Actually, the problem was in the red colored line of code.

Each time we increment the row count of DataGridView, it's clearing out the data. But, this is not alway done.
So, the solution for such a problem is shown below.
  1. Dim sadapt As New OleDbDataAdapter("SELECT * FROM [OrderDetail],[Order] WHERE [Order].Transaction=[OrderDetail].Transaction AND OrderNo='" & cboOrderNo.Text & "'", con)  
  2. Dim ds As DataSet = New DataSet  
  3. Dim trans As String = ""  
  4. sadapt.Fill(ds)  
  5. dgvDetails.Rows.Clear()  
  6. dgvDetails.RowCount = dgvDetails.RowCount + 1  
  7. For intRow = 0 To ds.Tables(0).Rows.Count - 1  
  8. dgvDetails.Rows(intRow).Cells("SrNo").Value = ds.Tables(0).Rows(intRow).Item("SrNo").ToString  
  9. dgvDetails.Rows(intRow).Cells("Particular").Value = ds.Tables(0).Rows(intRow).Item("Particular").ToString  
  10. dgvDetails.Rows(intRow).Cells("Barcode").Value = ds.Tables(0).Rows(intRow).Item("PlainTees").ToString  
Conclusion
 
I hope this will help others who have been stuck in the same problem.

 

Ebook Download
View all
Learn
View all