Using Datareader with label control

Hi EE Experts:

How do you bind data to a single label control?

Code:

<script runat="server">
    Protected Sub Page_Load(ByVal sender As Object, _
            ByVal e As System.EventArgs)

        If Not Page.IsPostBack Then
            Dim MyConnection As SqlConnection
            Dim MyCommand As SqlCommand
            Dim MyReader As SqlDataReader

            MyConnection = New SqlConnection()
            MyConnection.ConnectionString = _              
       ConfigurationManager.ConnectionStrings("DSN_Northwind").ConnectionString

            MyCommand = New SqlCommand()
            MyCommand.CommandText = "SELECT ID, CustomerName FROM CUSTOMERS"
            MyCommand.CommandType = CommandType.Text
            MyCommand.Connection = MyConnection

            MyCommand.Connection.Open()
            MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)

           ??????????????????????  WHAT GOES HERE  ?????????????????????

            MyCommand.Dispose()
            MyConnection.Dispose()
        End If
    End Sub
</script>

Then, in the page:

<asp:Label ID="Label1" runat="server" Text="Label"><%# CustomerName %></asp:Label>

Is this possible in ASP.NET?  I don't want to use gridview, detailsview, formview, repeater, etc...  I just want to quickly bind a headline or single database field to a label or literal control.

Chris
jumpseatnewsAsked:
Who is Participating?
 
gtmljscCommented:
The simplest way is:

If (MyReader.Read())
Begin
Label1.Text = MyReader("CustomerName").ToString()
End

In your aspx file:

<asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
0
 
Jojo1771Commented:
gtmljsc  is correct.

No points wanted but heres some advice Chris.

You never have to use gridview, detailsview, formview, repeater, etc...  

You can always read you data directly and put it to any control, as you can do any code you want between the reader

  MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)
While MyReader.read
Dim blah1 as string  = MyReader("Bah")
Label1.text  = blah1
'and so on
end while

You can aslo store your data in a dataset and call the data later in your page, so you don't have so much code in you reader, if you only have 1 row coming back then it makes more sense to assign the data to a class or local variables.
0
 
jumpseatnewsAuthor Commented:
Thanks to you both!  This was exactly what I was looking for.

EE Rocks!!!!!!

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.