ASP.net将数据库模型编号放入数组中

时间:2012-08-09 20:09:00

标签: asp.net mysql arrays gridview

嘿所有我想弄清楚如何在循环时将我的数据库中的一些模型编号添加到数组中。

这是我的代码:

objCmd = New MySqlCommand(strSQL, objConn)
dtReader = objCmd.ExecuteReader()

If dtReader.HasRows() Then
   grdViewItems.DataSource = dtReader
   grdViewItems.DataBind()

   Dim arrayOfItems As String() = New String() {}

   While dtReader.Read()
        arrayOfItems(intX) = dtReader.GetString("model_number")
        'arrayItems(intX) = dtReader.GetString("model_number")
        intX += 1
   End While

   'Session.Add("arrayOfItems", arrayItems)
   Session("arrayOfItems") = arrayOfItems

   dtReader.Close()
   dtReader = Nothing
   objConn.Close()
   objConn = Nothing
End If

问题是它永远不会使用值填充数组(尽管这些值存在于gridview中,因为它会跳过while循环中值的读取。

我在这里做错了什么?

完整代码

Dim intX As Integer = 0

    objConn = New MySqlConnection(product.strConnString)
    objConn.Open()

    strSQL = "SELECT prod.id, PP.model_number, description, price, price_new, price_direct, price_builder " & _
             "FROM product as prod " & _
                "INNER JOIN product_price as PP ON PP.product_id = prod.type " & _
             "WHERE prod.id = " & pageID & ";"

    Try
        objCmd = New MySqlCommand(strSQL, objConn)
        dtReader = objCmd.ExecuteReader()

        If dtReader.HasRows() Then
            grdViewItems.DataSource = dtReader
            grdViewItems.DataBind()

            Dim arrayOfItems As New List(Of String)()

            For Each row As GridViewRow In grdViewItems.Rows
                arrayOfItems(intX) = row.Cells(0).Text.ToString
                intX = intX + 1
            Next

            MsgBox(arrayOfItems(0))

            'Session.Add("arrayOfItems", arrayItems)
            Session("arrayOfItems") = arrayOfItems

            dtReader.Close()
            dtReader = Nothing
            objConn.Close()
            objConn = Nothing
        End If
    Catch ex As Exception
        MsgBox("LoadProductItems: " & ex.Message)
    End Try

2 个答案:

答案 0 :(得分:0)

我建议使用List of int or string

而不是数组

答案 1 :(得分:0)

看起来问题出在你的循环中。替换以下代码

Do While dtReader.Read
   arrayOfItems(intX) = dtReader.GetString("model_number")
   intX += 1
Loop

'with this code
While dtReader.Read()
     arrayOfItems(intX) = dtReader.GetString("model_number")
     intX += 1
End While

更新答案: 将数据分配给gridview时,还要将数据保存在像这样的数据表中

Dim dt As DataTable = New DataTable
dt = dtReader

`Then get the data from the table
Dim i As Integer = 0
Do While (i < dt.Rows.Count)
dt.Rows(i)("COlumnName").ToString
i = (i + 1)
Loop

再次更新答案: 从gridview中读取数据

For Each row As GridViewRow In grdViewItems.Rows
   arrayOfItems(intX) = row.Cells(0).Text.ToString ` in cell specify the index of the model_number column
   intX = intX + 1
Next