Introduction :
ASP.NET provides several Web controls that make displaying data on a Web page easier than ever before. This chapter shows you how to take advantage of a process called data-binding to easily display data in a variety of formats using very little code. This chapter covers many of the most commonly used features of the Repeater, DataList, and DataGrid, including some fairly advanced DataGrid features. Using these data-bound Web controls, it is very easy to write data-driven Web Forms by just dragging and dropping a few controls onto a form and writing a few lines of code.
Rendering Data Directly on a Web Form :
You want to display a piece of data on a Web Form using data-binding
Technique
The Repeater control is the simplest of three templated data-bound controls provided with ASP.NET (the others being the DataList and DataGrid). It supports templates for Header, Item, AlternatingItem, Separator, and Footer, which can each contain static and dynamic (data-bound) content. The following example demonstrates how to set up a Repeater's templates and how to data-bind the Repeater to a dataset.
The ASPX page is as follows:
<asp:Repeater id="Repeater1" runat="server"> <HeaderTemplate>Customers:<br/><ul></HeaderTemplate> <ItemTemplate> <li><%#DataBinder.Eval(Container.DataItem, "CompanyName")%>, <%#DataBinder.Eval(Container.DataItem, "ContactName")%></li> </ItemTemplate> <AlternatingItemTemplate> <li><font color="red"> <%#DataBinder.Eval(Container.DataItem, "CompanyName")%>, <%#DataBinder.Eval(Container.DataItem, "ContactName")%></font></li> </AlternatingItemTemplate> <FooterTemplate><hr/>Data Retrieved at: <%# System.DateTime.Now.ToString() %></FooterTemplate> </asp:Repeater> <br> <br> <asp:Label id="errorMsgLabel" runat="server" Width="327px" Height="111px"></asp:Label>
In <script runat="server" /> block or codebehind:
Sub BindRepeater() 'object vars Dim sqlConnection As SqlConnection Dim sqlDataAdapter As SqlDataAdapter Dim sqlCommand As SqlCommand Dim dataSet As DataSet Dim dataTable As DataTable Try sqlConnection = New SqlConnection("Integrated Security=yes; _ Initial Catalog=Northwind; _ Data Source=(local)") 'pass the stored proc name and SqlConnection sqlCommand = New SqlCommand("Select * From Customers", _ sqlConnection) 'instantiate SqlAdapter and DataSet sqlDataAdapter = New SqlDataAdapter(sqlCommand) dataSet = New DataSet() 'populate the DataSet sqlDataAdapter.Fill(dataSet, "Customers") 'apply sort to the DefaultView to sort by CompanyName dataSet.Tables(0).DefaultView.Sort = "CompanyName" Repeater1.DataSource = dataSet.Tables("Customers").DefaultView Repeater1.DataBind() Catch exception As Exception errorMsgLabel.Text = exception.ToString() End Try End Sub
No comments:
Post a Comment