簡體   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