Best way to display a label with text from db?

K

Kees de Winter

Hi,

If I want to display some text value coming out of a database on an aspx
page (on a label), do I really have to create a connection and command
object etc. all manually (such as in the code below) or is there an easier
way (asp.net 2.0, VS 2005) ?

Thanks for your help!

Protected Sub Page_Load(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Me.Load
Dim myConnection As SqlConnection = New
SqlConnection(ConfigurationManager.ConnectionStrings("DevDbConnectionString"
).ToString)
If Not Page.IsPostBack Then
Dim strQuery As String = "SELECT CategoryID FROM Category WHERE
CategoryURL='" + Page.Request("dir") + "'"
Dim myCommand As New SqlCommand(strQuery, myConnection)
myConnection.Open()
Dim strCategoryID As String
strCategoryID = myCommand.ExecuteScalar
myConnection.Close()
End If
[..]
End Sub
 
S

sloan

At the very very least, I'd create a WebUserControl (ascx) file. to
encapsulate the logic.

You can then drag and drop these onto your form when you need it.

I personally don't like writing data access code in the persentation
layer...but you'll have decide what to do there.

Right Click... Add New Item ... Web User Control

Drag a label onto it.

create a Public Property .. to use as you key (or "dir" in your case)

...

If you want shorter lined dataaccess code, considere the EnterpriseLibrary
Data Access block. search msdn and you'll find it.

it has a small learning curve, but the payoff is well worth it. You could
get your code down to 1 to 3 lines to get your value.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top