How to bind data to repeater control in asp.net c#


A repeater in asp.net: In this tutorial, I am going to discuss the how-to bind data to repeater control in asp.net c#, we will also discuss about crud operation with "repeater control" in asp.net.

Why "Repeater in asp.net" 
In Repeater control, the Data records to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.


Repeater in asp.net,repeater control
Repeater in asp.net 

The actual use of  repeater control is to display a list of data from the sql server ,we can also use many more data source to display the record on repeater in asp.net.

Here are the some list of templates which is used with repeater control 

1.Item Template
2.Header Template
3.Footer Template
4.Separator Template
5.Alternating Item Template 

#Step 1: Now, I am going to show you how you can implement repeater control in asp.net .  First, you have to create a table to store data of  repeater control

create database Repeater_control
use Repeater_control

create table repeaterinaspnet
(
pid int identity primary key,
Name varchar(50),
Price varchar(50),
Pic varchar(50)
)



create proc usp_product_get
as
 begin
select * from repeaterinaspnet
end

create proc sp_product_insert
@Name varchar(50),
@Price varchar(50),
@Pic varchar(50)
as
 begin
insert into repeaterinaspnet(Name,Price,Pic)values(@Name,@Price,@Pic)
end

create proc usp_product_delete
@pid int,
@pic varchar(1000) output
as
 begin
  select @pic=pic from repeaterinaspnet
delete from  repeaterinaspnet where pid=@pid
end

ALTER proc sp_product_update
@pid int,
@Name varchar(50),
@Price varchar(50),
@Pic varchar(50)
as
 begin
  update repeaterinaspnet set Name=@Name,Price=@Price, @Pic=pic where pid=@pid

end

#Step 2: Now add a connection in web..config file

<configuration>
<connectionStrings>
  <add connectionString ="data source=SANJAY\SQL2012; initial catalog=DBUPLOAD; integrated security=true;" name ="reapterconnection"/>
</connectionStrings>
    <system.web>
      <compilation debug="true" targetFramework="4.5.2" />
      <httpRuntime targetFramework="4.5.2" />
    </system.web>

</configuration>

#Step 3: Add a asp.net c# webform , in my case my webform name is repeater_control _in_aspnet.aspx.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="repeater_in_aspnet.aspx.cs" Inherits="repeater_in_aspnet" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Name :</td>
                    <td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Price :</td>
                    <td>
                        <asp:TextBox ID="txt_price" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Pic :</td>
                    <td>
                        <asp:FileUpload ID="fupic" runat="server"></asp:FileUpload></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Button ID="btn_save" runat="server" Text="Save" OnClick="btn_save_Click" /></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <asp:Repeater ID="RepDetails" runat="server" OnItemCommand="RepDetails_ItemCommand">
                            <HeaderTemplate>
                                <table style="border: 1px solid #df5015; width: 500px" cellpadding="0">
                                    <tr style="background-color: #df5015; color: White">
                                        <td>
                                            <b>Name</b>
                                        </td>
                                        <td>
                                            <b>Price</b>
                                        </td>
                                        <td>
                                            <b>Pic</b>
                                        </td>
                                        <td></td>
                                        <td></td>
                                    </tr>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <tr style="background-color: #EBEFF0">
                                    <td>
                                        <%#Eval("Name"%>
                                    </td>
                                    <td>
                                        <%#Eval("Price"%>
                                    </td>
                                    <td>
                                        <asp:Image ID="Image1" runat="server" Width="70px" Height="50px" ImageUrl='<%#Eval("Pic","~/repeaterdata/{0}"%>' />
                                    </td>
                                    <td>
                                        <asp:LinkButton ID="lnkbtnedit" runat="server" Text="Edit" CommandArgument='<%#Eval("PID"%>' CommandName="EDT"></asp:LinkButton>
                                    </td>
                                    <td>
                                        <asp:LinkButton ID="lnkbtndelete" runat="server" Text="Delete" CommandArgument='<%#Eval("PID"%>' CommandName="DLT"></asp:LinkButton>
                                    </td>
                                </tr>
                            </ItemTemplate>
                            <FooterTemplate>
                                </table>
                            </FooterTemplate>
                        </asp:Repeater>

                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


#Step 4: Come to the repeater_control _in_aspnet.aspx.cs page

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Web.UI.HtmlControls;

public partial class repeater_in_aspnet : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["reapterconnection"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            Fill_Reapter();
        }
    }
    //Bind the repeater control
    public void Fill_Reapter()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("usp_product_get", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            RepDetails.DataSource = ds;
            RepDetails.DataBind();
        }
        else
        {
            RepDetails.DataSource = null;
            RepDetails.DataBind();
        }

        con.Close();
    }
     //Button to insert data in repeater control
    protected void btn_save_Click(object sender, EventArgs e)
    {
        string FN = "";
        if (btn_save.Text == "Save")
        {
            FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fupic.PostedFile.FileName);
            fupic.SaveAs(Server.MapPath("repeaterdata" + "\\" + FN));
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_product_insert", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Price", txt_price.Text);
            cmd.Parameters.AddWithValue("@Pic", FN);
            cmd.ExecuteNonQuery();
            con.Close();
        }
        else if (btn_save.Text == "Update")
        {
            FN = Path.GetFileName(fupic.PostedFile.FileName);
            con.Open();
            SqlCommand cmd = new SqlCommand("sp_product_update", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pid", ViewState["PID"]);
            cmd.Parameters.AddWithValue("@Name", txt_name.Text);
            cmd.Parameters.AddWithValue("@Price", txt_price.Text);
            if (FN != "")
            {
                FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(fupic.PostedFile.FileName);
                cmd.Parameters.AddWithValue("@Pic", FN);
                File.Delete(Server.MapPath("repeaterdata" + "\\" + ViewState["PIC"]));
                fupic.SaveAs(Server.MapPath("repeaterdata" + "\\" + FN));
            }
            else
            {
                cmd.Parameters.AddWithValue("@Pic", ViewState["PIC"]);
            }
            cmd.ExecuteNonQuery();
            con.Close();
        }
        Fill_Reapter();
    }

     //Edit and update event for the repeater control
    protected void RepDetails_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        int PID = int.Parse(e.CommandArgument.ToString());
        if (e.CommandName == "EDT" && PID > 0)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_product_get", con);
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                DataView dv = new DataView(ds.Tables[0]);
                dv.RowFilter = "PID=" + PID;
                DataTable dt = new DataTable();
                dt = dv.ToTable();
                txt_name.Text = dt.Rows[0]["Name"].ToString();
                txt_price.Text = dt.Rows[0]["Price"].ToString();
                ViewState["PIC"] = dt.Rows[0]["Pic"].ToString();
                ViewState["PID"] = PID;
                btn_save.Text = "Update";
            }
        }
        else if (e.CommandName == "DLT" && PID > 0)
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_product_delete", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@pid", PID);
            SqlParameter param = cmd.Parameters.Add("@pic"SqlDbType.VarChar, 200);
            param.Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();
            con.Close();
            string FF = cmd.Parameters["@pic"].Value.ToString();
            File.Delete(Server.MapPath("repeaterdata" + "\\" + FF));
            Fill_Reapter();
        }
    }
}



I hope you will like this article about repeater in asp.net. Hit the share button and help us.

Post a Comment

Post a Comment (0)

Previous Post Next Post