【问题标题】:How to show every row and colums data from a database to Datagridview如何将数据库中的每一行和每一列数据显示到 Datagridview
【发布时间】:2023-04-02 02:20:01
【问题描述】:

我遇到了一个问题,我从数据库中选择要在网格中显示的行:因此,网格上只显示了一行,其余的没有显示。

这是我的代码:

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

【问题讨论】:

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

标签: vb.net sqlcommand


【解决方案1】:

问题似乎出在您的 SQL 查询中。

where Req_No=" & TextBox1.Text & "

上面的这部分查询会将返回的行限制为只有一行。

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

where Req_No LIKE %" & TextBox1.Text & "

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-03-05
      • 2013-11-18
      相关资源
      最近更新 更多