将查询返回到stringbuilder

时间:2014-03-16 19:11:18

标签: asp.net stringbuilder

我只想尝试将查询返回到stringbuilder中以生成动态html

Partial Class _Default
    Inherits System.Web.UI.Page              
    <WebMethod()> _
    Public Shared Function BuscarTurbos(referencia As String) As String
        Dim sb As StringBuilder = New StringBuilder
        Dim conexion As SqlConnection = New SqlConnection("Data Source=PC-TOSH\misql ;Initial Catalog=Rotomaster;Integrated Security=True")
        conexion.Open()
        Dim cmd As SqlCommand
        cmd = New SqlCommand("SELECT VehicleModel,Year FROM TURBOSNUEVO WHERE TurboModel like '%" + referencia + "%'", conexion)
        Dim dr As SqlDataReader = cmd.ExecuteReader()
        If dr.HasRows Then
            While dr.Read
                sb.Append("<p style='background-color:red;width:50%;height:100px'>'" + dr("VehicleModel").ToString(), CType(dr("Year"), Double) + "' </p>")
            End While
        End If    
        Return sb.ToString    
    End Function
End Class

1 个答案:

答案 0 :(得分:0)

我会改变你的

sb.Append("<p style='background-color:red;width:50%;height:100px'>'" + dr("VehicleModel").ToString(), CType(dr("Year"), Double) + "' </p>")

进入这个:

sb.AppendFormat("<p style='background-color:red;width:50%;height:100px'>{0} {1}</p>", dr("VehicleModel").ToString(), dr("Year").ToString())

关于字符串连接(连接在一起)的一个注释 - 字符串是不可变的意味着每次将字符串连接在一起时,它必须创建一个新的字符串对象,因为它们无法更改。通过使用AppendFormat,它可以使您不必创建额外的字符串对象。