Friday 26 September 2014

Asphelp: Bind asp repeater with database

Download Source
In this article you will learn how to bind Sql server Table and show the record of table in asp repeater. Sql server used for database and visual studio for design and developing

Create Table
CREATE TABLE [dbo].[employee] (
    [Id]   INT          IDENTITY (1, 1) NOT NULL,
    [name] VARCHAR (50) NULL,
    PRIMARY KEY CLUSTERED ([Id] ASC)
);

HTML CODE
<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style>
        #tbl1 {
            border: 3px #fff solid;
            padding: 10px;
            margin: 5px;          
            width:400px;  
            box-shadow: 3px 5px 15px #b6b6b6;
        }

            #tbl1:hover {
                border: #ffd926 3px solid;
                padding: 10px;
                margin: 5px;                
                box-shadow: 3px 5px 15px #b6b6b6;
            }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div align="center">
            <asp:Repeater ID="rptbind" runat="server">
                <ItemTemplate>
                    <table id="tbl1" style="background-color: white">
                        <tr>
                            <td>Employee ID : <%#Eval("id") %>
                            </td>                           
                            <td align="left">Employee Name : <%#Eval("name") %>
                            </td>
                        </tr>
                    </table>
                </ItemTemplate>
            </asp:Repeater>
        </div>
    </form>
</body>
</html>

C# CODE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

namespace Datalist
{
    public partial class Home : System.Web.UI.Page
    {
        SqlConnection con = new SqlConnection("Data Source=Servername;Initial Catalog=Databasename;Integrated Security=True");

        protected void Page_Load(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select * from employee", con);
            SqlDataAdapter ad = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            rptbind.DataSource = ds.Tables[0];
            rptbind.DataBind();
            con.Close();
        }
    }
}


Output Preview

bind repeater | dotnetasphelp


Download Source

No comments: