How to Create DataList from SqlDataSource in Asp.Net


DataList Controls in Nothing but Store the List of values and display in meaningful output. Here we will create DataList Controls and Bind Data from Database using SqlDataSource and design DataList Controls like what we design Gridview. In DataList Controls we can set Header, footer Style or SelectedItemStyle etc… We can create Item Template and Design tables in DataList Control. Let’s Start to Create DataList Control.

Create table in Database and fill some data.

CREATE TABLE [dbo].[Customers](
      [ContactName] [varchar](20) NOT NULL,
      [City] [varchar](20) NOT NULL,
      [PostalCode] [int] NOT NULL,
      [Country] [varchar](20) NOT NULL,
      [Phone] [bigint] NOT NULL,
      [Fax] [bigint] NOT NULL,
      [CustomerId] [int] IDENTITY(1,1) NOT NULL,
 CONSTRAINT [PK_Customers] PRIMARY KEY CLUSTERED
(
      [CustomerId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 1: Design your Webpage like below.

<div>
<asp:DataList ID="dlCustomers" runat="server" DataSourceID="SqlDataSource1" RepeatColumns="3" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Horizontal">
<FooterStyle BackColor="#CCCC99" ForeColor="Black" />
<HeaderStyle BackColor="#333333" Font-Bold="True" ForeColor="White" />
<ItemTemplate>
  <table class="table">
    <tr><th colspan="2"><b><%# Eval("ContactName") %></b></th></tr>
    <tr><td colspan="2">
        <%# Eval("City") %>,
        <%# Eval("PostalCode") %><br />
        <%# Eval("Country")%></td></tr>
    <tr><td>Phone: </td><td><%# Eval("Phone")%></td></tr>
    <tr><td>Fax: </td><td><%# Eval("Fax")%></td></tr>
  </table>
</ItemTemplate>
<SelectedItemStyle BackColor="#CC3333" Font-Bold="True" ForeColor="White" />
</asp:DataList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:UHConnection %>"
SelectCommand = "SELECT * FROM Customers"> </asp:SqlDataSource>
</div>

Step 2: Now Select SqlDataSource and Configure Data Source. After based on Server Configuration Select DataSource and Assign table in SqlDataSource.

Step 3: Now After Configuration SqlDataSource run your webpage in browser and see output.



Related Posts

Previous
Next Post »

Thanks for comments.....