2013-03-04 19 views
0

我從表中讀取數據時遇到問題。這是我的編碼無法讀取多於一行的數據

Dim SqlQry As String = "SELECT Distinct(RechargeAmt) from KioskItem where TelcoID='" & TelcoID & "'" 
     Dim SqlCmd As New SqlCommand(SqlQry, Conn) 
     Dim dr As SqlDataReader = SqlCmd.ExecuteReader 
     dr.Read() 
     If dr.HasRows Then 
      While dr.Read() 
       Dim SqlQry As String = "SELECT Distinct(RechargeAmt) from KioskItem where TelcoID='" & TelcoID & "'" 
     Dim SqlCmd As New SqlCommand(SqlQry, Conn) 
     Dim dr As SqlDataReader = SqlCmd.ExecuteReader 
     dr.Read() 
     If dr.HasRows Then 
      While dr.Read() 
       RechargeAmt = dr(0) 
       a = a & RechargeAmt & ";" 
      End While 
     End If 
     If a = 0 Then 
      Return RechargeAmt 
     Else 
      Return a 
     End If   

我的問題是:如果數據有多個行,它沒有任何問題的數據保存到一個字符串,但是當我的表中的數據只有一個rowm,它是在樣品無法讀取數據。我嘗試這個

If dr.HasRows Then 
      RechargeAmt = dr(0) 
      While dr.Read() 
       a = a & RechargeAmt & ";" 
      End While 
     End If 
     If a = 0 Then 
      Return RechargeAmt 
     Else 
      Return a 
     End If  

,但它仍然無法從表

回答

1

那是因爲你總是缺少的第一行讀取數據。

看到這裏

dr.Read()    //Gets the first row 
    If dr.HasRows Then 
     While dr.Read() //Gets the second row onwards 

你總是跳過第一行。

初始讀取不是必需的。你可以用

While dr.Read() 

控制直接啓動會去只如果有行內循環。