来自DB reader的vb.net数组字符串

时间:2014-08-28 19:25:03

标签: vb.net

寻找以下格式从我的数据库中获取日期字符串的最佳方法: Session("AssignedLeave") = = "1/2/2015","3/15/2015","12/25/2015",ect... 我已经开始了,但无法弄清楚附加到数组并在我的循环内/外执行它?我在数据库中有23个字段,我的i=4to27正确地获取日期...

 ' Fill Sessions with user data from PICKS table of the DB
    objConn = New Data.OleDb.OleDbConnection(strConnection)
    objCmd = New Data.OleDb.OleDbCommand("SELECT * FROM ResultsRound4 WHERE FDID = @FDID", objConn)
    objCmd.Parameters.AddWithValue("@FDID", Session("FDID"))
    Dim MyLv As Array()
    Try
        objConn.Open()
        objRdr = objCmd.ExecuteReader()
        While objRdr.Read()
            for i As Integer =4 to 27
                Session("AssignedLeave") = objRdr.Item(i)
                response.write(i)
            next
        End While
        objRdr.Close()
        objConn.Close()
    Catch ex As Exception
        Response.Write(ex)
    Finally
        objConn.Close()
    End Try

FINAL FIX是:

    Try
        objConn.Open()
        objRdr = objCmd.ExecuteReader()
        Dim sb = new StringBuilder()
        While objRdr.Read()
            for i As Integer = 4 to 27
                If objRdr.Item(i) IsNot DBNull.Value Then
                    sb.Append("""" + objRdr.Item(i).ToShortDateString() + """,")
                End If  
            next
        End While
        sb.Length -= 1 'remove the last comma
        Session("AssignedLeave") = sb.ToString()

        objRdr.Close()
        objConn.Close()
    Catch ex As Exception
        Response.Write(ex)
    Finally
        objConn.Close()
    End Try

2 个答案:

答案 0 :(得分:1)

您可以填写List(Of string),然后使用String.Join连接它们:

Dim list = New List(Of String)
If objRdr.Read()
    For i As Int32 = 4 To 27
        list.Add(objRdr.GetString(i))
    Next
End If
Session("AssignedLeave") = String.Join(",", list)

但是,为什么在表中存储Date String,为什么要将行存储为列?

如果它们是Date,并且您希望在没有时间的情况下输出它们date.ToString("d")dt.ToShortDateString,那么这是您当前文化的日期格式。否则,您可以使用:dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)

强制它

例如:

Dim list = New List(Of String)
If objRdr.Read()
    For i As Int32 = 4 To 27
        list.Add(objRdr.GetDateTime(i).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture))
    Next
End If

答案 1 :(得分:1)

我会使用StringBuilder,在StringBuilder中附加所需的相应格式的每个项目,并在循环之后将整个字符串分配给会话变量

   Dim sb = new StringBuilder()
   While objRdr.Read()
        for i As Integer = 4 to 27
            If Not objRdr.IsDBNull(i) Then 
                sb.Append("""" + objRdr(i).ToShortDateString() + """,")
            End If
        next
    End While
    sb.Length -= 1 'remove the last comma
    Session("AssignedLeave") = sb.ToString()