deha
deha

Reputation: 815

How bind single record data to controls in ASP.NET?

Which is the best control/approach in ASP.NET 4 to bind data from single record, which is fetched from sql server? I have some page to display text, so I need labels like title, date of publication, content and so on - single label for each data. Of course I can use ListView or Repeater, but I wonder if there's some other way.

Thanks in advance

Upvotes: 3

Views: 2033

Answers (3)

Tim
Tim

Reputation: 28540

You could use the DetailsView, which is designed to display a single record (though it's usually used in a master-details scenario). DetailsView can use SqlDatasource.

Trivial example:

<asp:SqlDataSource id="slqDataSource1" runat="server"
     ConnectionString="<%$ ConnectionStrings:MyConnectionString %>"
     SelectCommand="SELECT * FROM Table" />

<asp:DetailsView id="detailsView1" runat="server"
     AutoGenerateRows="true" DataKeyNames="Id"
     DataSourceID="sqlDataSource1" />

The above example creates a DetailsView based on the SelectCommnad of the SqlDataSource. In the implementation above, since AutoGenerateRows is set to true the control will render the data. However, you can also specify the fields explicitly, and have different fields you can choose from (BoundField, ButtonField, CheckBoxField, etc).

DetailsView Class

Upvotes: 2

cgcarter1
cgcarter1

Reputation: 327

You can not bind data to a textfield. However, using a reader like the one listed above creates a WHOLE bunch of unneeded overhead. Why not create a class? This way you fetch it in your DAL and then do some processing (or conversion) in your BLL.

Be the way I would do it anyways. DataReaders and DataSets should not be used unless you are binding.

Upvotes: 0

Chains
Chains

Reputation: 13167

sqldatareader is a good one.

you can create a sql-command, and then use the .executereader method. For example:

dim myReader as SqlDatareader
Dim myCommand As New SqlCommand("myStoredProcedure", myConnection)
        With myCommand
            .CommandType = CommandType.StoredProcedure
            With .Parameters
                .Clear()
                .AddWithValue("myParameter", parametervalue)
            End With
        End With
Try
   myConnection.open
   myReader = myCommand.ExecuteReader
   While myReader.Read
       Me.myTextBox.Text = myReader("fieldname")
       Me.myCheckbox.Checked = myReader("fieldname")
   End While
Catch ex As Exception
   Response.Write(ex.Message)
Finally
   myConnection.Close()
End Try

or some such...

Upvotes: 2

Related Questions