ASP.NET (.VB) - Anvendelse af count (SQL) - kan det skrives pænere
Hej.På en webside ønsker jeg at hente nogle nyheder ind i min webside. Der er plads til de seneste 6 nyheder på forsiden. For at siden ikke ser dum ud vil jeg gøre nogle elementer usynlige så fremt der ikke er op til 6 nyheder pt. 8ellers står labelens standardtekst og forvirrer.
Kan nedenstående kode skrivs bedre og pænere? (Den er ikke fuldent)
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim NewsConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("FrejaConnectionString").ConnectionString)
Dim NewsReader As SqlDataReader
Dim NewsCommand As SqlCommand
Dim NewsSQL As String = ""
NewsSQL = "SELECT TOP 6 Overskrift, LEFT(Indhold, 5000) AS Indhold, Forfatter, Dato FROM nyheder ORDER BY Dato"
NewsCommand = New SqlCommand(NewsSQL, NewsConnection)
Dim AntalSQL As String = ""
AntalSQL = "SELECT count(*) as antalnyheder FROM nyheder"
Dim AntalCommand As SqlCommand = New SqlCommand(AntalSQL, NewsConnection)
NewsConnection.Open()
NewsReader = NewsCommand.ExecuteReader()
Dim lblOverskriftArr As Label() = New Label() {lblNyhed1Overskrift, lblNyhed2Overskrift, lblNyhed3Overskrift, lblNyhed4Overskrift, lblNyhed5Overskrift, lblNyhed6Overskrift}
Dim lblDatoArr As Label() = New Label() {lblNyhed1Dato, lblNyhed2Dato, lblNyhed3Dato, lblNyhed4Dato, lblNyhed5Dato, lblNyhed6Dato}
Dim lblIndholdArr As Label() = New Label() {lblNyhed1Indhold, lblNyhed2Indhold, lblNyhed3Indhold, lblNyhed4Indhold, lblNyhed5Indhold, lblNyhed6Indhold}
Dim i As Integer = 0
While NewsReader.Read = True
lblOverskriftArr(i).Text = NewsReader("Overskrift").ToString.Trim()
'lblDatoArr(i).Text = CType(NewsReader("NyhedsDato"), DateTime).ToString("dddd")
lblNyhed1Dato.Text = CType(NewsReader("Dato"), DateTime).ToString("dddd d. MMMM yyyy")
'lblDatoArr(i).Text = CType(NewsReader("Dato"), DateTime).ToString("dddd 'd.' d. MMMM yyyy") + CType(NewsReader("Tid"), DateTime).ToString("' kl. ' HH.mm")
lblIndholdArr(i).Text = Server.HtmlDecode(NewsReader("Indhold").ToString.Trim())
i = i + 1
End While
NewsReader.Close()
Dim AntalREader As SqlDataReader
AntalREader = AntalCommand.ExecuteReader()
Dim Antal As Integer
AntalREader.Read()
Antal = AntalREader("antalnyheder")
If Antal = 2 Then
lblNyhed2Dato.Visible = False
End If
AntalREader.Close()
NewsConnection.Close()
End Sub
End Class