繁体   English   中英

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

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

我面临一个问题,我正在从数据库中选择要显示在网格中的行:结果,网格上仅显示了一行,其余的则没有显示。

这是我的代码:

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()

看来问题出在您的SQL查询中。

where Req_No=" & TextBox1.Text & "

上面的查询部分将返回的行限制为仅一行。

我建议将上面的查询替换为:

where Req_No LIKE %" & TextBox1.Text & "

这将返回与输入文本相似的带有“ Req_No”的行,而不是与输入文本相同的带有“ Req_No”的行。

如果您未实现搜索功能。 完全删除Where子句。

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