将 DataGridView 中的值与 MySQL 进行比较(如果它们共享相同的 ID)

Comparing values in a DataGridView against MySQL if they share the same ID

我正在尝试使用“ID”将 DataGridView 中一列中的值与 MySQL Table 中的一列中的值进行比较。当程序在 DataGridView 中循环时,我采用的方法是提取 MySQL 中的库存量,将其放入文本框并将其与 DataGridView 中的库存量进行比较。如果 DataGridView 中的数字更大,文本框将显示:“Stock falls below 0”。如果 MySQL table 中的数字更大,文本框将改为显示“Stock remains above or equals 0”。

我将在下面突出显示确切的行,但是当我尝试 运行 代码时,会弹出此错误:

MySql.Data.MySqlClient.MySqlException: 'Invalid attempt to access a field before calling Read()'

我不确定为什么会出现此错误。我在项目的其他部分使用了非常相似的代码,没有任何抱怨。

这是我的尝试:

Dim cmd As MySqlCommand
Dim READER As MySqlDataReader
For i = 0 To DataGridView1.Rows.Count - 1
            Dim Query As String
            Query = "SELECT Quantity FROM `database`.`stockroom` WHERE `ID`='@Stock'"
            COMMAND = New MySqlCommand(Query, MysqlConn)
            READER = COMMAND.ExecuteReader
            Sum_Quantity.Text = READER.GetString("Quantity") 'Error appears here

     If Sum_Quantity.Text >= DataGridView1.Rows(i).Cells(4).Value.ToString() Then 'IF STOCK REMAINS ABOVE OR EQUAL TO 0
            Sum_Outcome.Text = "Stock remains above or equals 0"
     ElseIf Sum_Result.Text <= DataGridView1.Rows(i).Cells(4).Value.ToString() Then 'IF STOCK REACHES BELOW 0
            Sum_Outcome.Text = "Stock falls below 0"
     End If
Next
  1. 打开你的连接。
  2. 将您的 ExecuteReader 调用换成 ExecuteScalar 并将其捕获为整数 - Dim qty = Convert.ToInt32(COMMAND.ExecuteScalar())
  3. 不要使用 >=<= 比较字符串 - it will go wrong 因为 "10" 小于 "2" - 将网格中的数量作为一个整数,并将其与数据库中的整数进行比较

您拥有的代码几乎毫无意义,因为如果循环,比如说,100 行,那么快地更改文本框 100 次,以至于您只会看到最后一次更改...

如果是我的问题,我可能会更像这样:

'imagine your grid is based on a datatable with the order info in
dt.Rows.Add("Apples", 1)
dt.Rows.Add("Pears", 2)
dt.Rows.Add("Bananas", 4)

'show the order in the grid
datagridviewX.DataSource = dt

所以想象一下,这就是您现在所要做的,上面。如果 DGV 正在查看具有更多列的 table,这将对我们有所帮助:

'add another columns to the table to hold the stock quantity and message
dt.Columns.Add("Stock", GetType(Integer))
dt.Columns.Add("Determination").Expression = "IIF([Quantity]>[Stock],'Not enough stock','Can fulfil this order')"

那么当我们要分析能够供货的订单时:

'loop over the table looking up the stock quants
Using cmd as New MySqlCommand("SELECT Quantity FROM Stock WHERE ID = @id", "conn str here")
  cmd.Parameters.AddWithValue("@id", "dummy value")
  cmd.Connection.Open()
  For Each ro as DataRow in dt.Rows
    cmd.Parameters("@id").Value = ro("Name").ToString()
    ro("Stock") = Convert.ToInt32(cmd.ExecuteScalar())
  Next ro
End Using

因此该代码将提取网格中所有项目的库存量并将其存储在“库存”列中。另外,字符串列上的表达式给出了是否有足够库存的评论。