Using Datareader with label control

Hi EE Experts:

How do you bind data to a single label control?


<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 = _              

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

            MyReader = MyCommand.ExecuteReader(CommandBehavior.CloseConnection)

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

        End If
    End Sub

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.

Who is Participating?
The simplest way is:

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

In your aspx file:

<asp:Label ID="Label1" runat="server" Text="Label1"></asp:Label>
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)
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.
jumpseatnewsAuthor Commented:
Thanks to you both!  This was exactly what I was looking for.

EE Rocks!!!!!!

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.