简体   繁体   中英

How to show every row and colums data from a database to Datagridview

I am facing a problem in which I am selecting rows from database to show in the grid: only a single row is showing on the grid as a result, the rest is not showing.

Here is my Code:

conn()
Dim qry As String = "select SN,Product_ID,Product_Description,Quantity,Supplier_Name from materialreq where Req_No=" & TextBox1.Text & ""

cmd = New SqlCommand(qry, cn)

dr = cmd.ExecuteReader()

Dim i As Integer = 0

While dr.Read() And i = DataGridView1.Rows.Count - 1

    DataGridView1.Rows(i).Cells("Column1").Value = dr("SN")
    DataGridView1.Rows(i).Cells("Column2").Value = dr("Product_ID")
    DataGridView1.Rows(i).Cells("Column3").Value = dr("Product_Description")
    DataGridView1.Rows(i).Cells("Column4").Value = dr("Quantity")
    DataGridView1.Rows(i).Cells("Column5").Value = dr("Supplier_Name")
    'DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells("Column3").Value = dr("Product_Description").ToString()
    'DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells("Column4").Value = dr("Quantity").ToString()
    'DataGridView1.Rows(DataGridView1.Rows.Count - 1).Cells("Column5").Value = dr("Supplier_Name").ToString()
    i = i + 1

End While

cn.Close()

It would seem like the problem lies within your SQL query.

where Req_No=" & TextBox1.Text & "

This part of the query above will limit the rows returned to only one row.

I would suggest replacing the query above with:

where Req_No LIKE %" & TextBox1.Text & "

This would return rows with "Req_No" that are similar to the entered text, instead of rows with "Req_No" that are identical to the entered text.

If you're not implementing a search function. Remove the Where clause altogether.

Make sure that select query is returning desired output( more than one row ) and you can use below mentioned code to read all data in a SqlDataReader

 If dr.HasRows Then
     While dr.Read
          DataGridView1.Rows(i).Cells("Column1").Value = dr("SN")
          DataGridView1.Rows(i).Cells("Column2").Value = dr("Product_ID")
          DataGridView1.Rows(i).Cells("Column3").Value = dr("Product_Description")
          DataGridView1.Rows(i).Cells("Column4").Value = dr("Quantity")
          DataGridView1.Rows(i).Cells("Column5").Value = dr("Supplier_Name")
    End While
 End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM