简体   繁体   English

如何显示从数据库到Datagridview的每一行和每一列的数据

[英]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. 看来问题出在您的SQL查询中。

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. 这将返回与输入文本相似的带有“ Req_No”的行,而不是与输入文本相同的带有“ Req_No”的行。

If you're not implementing a search function. 如果您未实现搜索功能。 Remove the Where clause altogether. 完全删除Where子句。

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 确保选择查询返回期望的输出( 多于一行 ),并且您可以使用下面提到的代码读取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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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