Friday 7 March 2014

Insert edit update delete in repeater control in asp.net

In this post I will Explain How to Insert, Edit, Update, Delete And display data or CRUD Operation in Repeater control.

The Repeater is control for used in asp.net to display the Entire table data. Repeater control is the best control to display repeated data. It allows to customization of the layout by each repeated list of item and do lots of design customization. The Repeater Control may be bound database file, database table, XML file and other file to control. The Repeater control is very use full Control to  display a repeated data that are bound to the control because we can create Table, Unordered lists, ordered list, anchor tags, Image galleries etc.

For Implementing Insert, Edit, Update and  delete Operation in Repeater first you have to create one table in database.
Create Table name is “dsh_RepeaterDemo"


Next step
1.Open Visual Studio
2.Create a new Project (ASP.NET Web Service) name it “RepeaterDemo” (You   can Also change Project name as you need.).

Next Step
Design aspx page In that page I am use three textbox and two button and one repeater control.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="RepeaterDemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style2
        {
            width: 79px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td class="style2">
                    Name:
                </td>
                <td>
                    <asp:TextBox ID="txtname" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Username:
                </td>
                <td>
                    <asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Password:
                </td>
                <td>
                    <asp:TextBox ID="txtpass" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                 
                    <asp:Button ID="btnsave" runat="server" Text="Save" OnClick="btnsave_Click" Height="23px"
                        Width="46px" />
                    &nbsp;
                    <asp:Button ID="btncancel" runat="server" Text="Cancel" Height="23px" Width="49px"
                        OnClick="btncancel_Click" />
                    &nbsp;
                </td>
            </tr>
        </table>
        <asp:Repeater ID="repeater" runat="server" OnItemCommand="OnItemCommand_repeater">
            <HeaderTemplate>
                <table border="1">
                    <tr>
                        <td>
                            <asp:Label ID="lblname" runat="server" Text="name"></asp:Label>
                        </td>
                        <td>
                            <asp:Label ID="lblusername" runat="server" Text="username"></asp:Label>
                        </td>
                        <td>
                            <asp:Label ID="lblpass" runat="server" Text="password"></asp:Label>
                        </td>
                    </tr>
            </HeaderTemplate>
            <ItemTemplate>
                <tr>
                    <td>
                        <asp:Label ID="labelID" Visible="false" runat="server" Text='<%#Eval("id") %>'></asp:Label>
                        <asp:Label ID="labelname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
                        <asp:TextBox ID="lbltxtname" runat="server" Visible="false" Text='<%#Bind("name") %>'></asp:TextBox>
                    </td>
                    <td>
                        <asp:Label ID="labelusername" runat="server" Text='<%#Eval("username") %>'></asp:Label>
                        <asp:TextBox ID="lbltxtusername" runat="server" Visible="false" Text='<%#Bind("username") %>'></asp:TextBox>
                    </td>
                    <td>
                        <asp:Label ID="labelpassword" runat="server" Text='<%#Eval("password") %>'></asp:Label>
                        <asp:TextBox ID="lbltxtpassword" runat="server" Visible="false" Text='<%#Bind("password") %>'></asp:TextBox>
                    </td>
                    <td>
                        <asp:ImageButton ID="imgedit" runat="server" CommandName="Edit" ImageUrl="img/edit-128.png"
                            Height="25" Width="25" />
                    </td>
                    <td>
                        <asp:ImageButton ID="imgdelete" runat="server" CommandName="Delete" ImageUrl="img/delete-24.png"
                            Height="25" Width="25" />
                    </td>
                </tr>
            </ItemTemplate>
            <FooterTemplate>
                <tr>
                    <td>
                        <asp:TextBox ID="txtftrname" runat="server" Visible="true"></asp:TextBox>
                    </td>
                    <td>
                        <asp:TextBox ID="txtftrusername" runat="server" Visible="true"></asp:TextBox>
                    </td>
                    <td>
                        <asp:TextBox ID="txtftrpassword" runat="server" Visible="true"></asp:TextBox>
                    </td>
                    <td>
                        <asp:LinkButton ID="lnkftrinsert" runat="server" Text="Insert" CommandName="Insert">
                        </asp:LinkButton>
                    </td>
                </tr>
                </table>
            </FooterTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>
Design of aspx page look like below figure.


Here I am used Stored Procedure to Perform Insert, Edit, Update and delete Operation in Repeater control.

StoredProcedure For Insert data to database :


StoredProcedure For Read Data From Database table :

StoredProcedure For Update Data to Database table :


StoredProcedure For Delete Data Of Database Table :


Next Step To code In Default.aspx.cs page
Default.aspx.cs

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.Configuration;
using System.Data;
namespace RepeaterDemo
{
    public partial class _Default : System.Web.UI.Page
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationTable"].ConnectionString.ToString());
        static int userid;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindRepeater();
            }
        }
     
        //Save Button
        protected void btnsave_Click(object sender, EventArgs e)
        {
            //Code For Update Data
            if (btnsave.Text == "Update")
            {
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.Connection.Open();
                cmd.CommandText = "usp_updateRepeaterDemo";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name", txtname.Text);
                cmd.Parameters.AddWithValue("@username", txtusername.Text);
                cmd.Parameters.AddWithValue("@password", txtpass.Text);
                cmd.Parameters.AddWithValue("@id", userid);
                cmd.ExecuteNonQuery();
                conn.Close();
                clearcontrol();
                BindRepeater();
                btnsave.Text = "Save";
            }
            else
            {
                //Code For Inserting Data to Database Table
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.Connection.Open();
                cmd.CommandText = "usp_RepeaterDemo";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name", txtname.Text);
                cmd.Parameters.AddWithValue("@username", txtusername.Text);
                cmd.Parameters.AddWithValue("@password", txtpass.Text);
                clearcontrol();
                Response.Write("Record Inserted Successfully!");
                cmd.ExecuteNonQuery();
                conn.Close();
                BindRepeater();
            }
        }
        //Method For Bind Data To Repeater Control
        private void BindRepeater()
        {
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.Connection.Open();
            cmd.CommandText = "usp_selectRepeaterDemo";
            cmd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);
            repeater.DataSource = dt;
            repeater.DataBind();
            conn.Close();
        }
        //Method for Clear Text From TextBoxes.
        private void clearcontrol()
        {
            txtname.Text = string.Empty;
            txtpass.Text = string.Empty;
            txtusername.Text = string.Empty;
        }
        protected void OnItemCommand_repeater(object source, RepeaterCommandEventArgs e)
        {
            //Code For Edit Record
            //On Commad Name Supplied to the Image Button-- "Edit" Button
            if (e.CommandName == "Edit")
            {
                //Getting Id of the selected record
                Label lblid1 = (Label)e.Item.FindControl("labelID");
                Label lblName = (Label)e.Item.FindControl("labelname");
                Label lblUsername = (Label)e.Item.FindControl("labelusername");
                Label lblPassword = (Label)e.Item.FindControl("labelpassword");
                userid = Convert.ToInt32(lblid1.Text);
                txtname.Text = lblName.Text;
                txtusername.Text = lblUsername.Text;
                txtpass.Text = lblPassword.Text;
                btnsave.Text = "Update";
            }
            //Code For Delete Record
            //On Commad Name Supplied to the Image Button-- "Delete" Button
            if (e.CommandName == "Delete")
            {
                ImageButton imgbtndelete = (ImageButton)e.Item.FindControl("imgdelete");
                //Getting Id of the selected record
                Label lblid1 = (Label)e.Item.FindControl("labelID");
                userid = Convert.ToInt32(lblid1.Text);
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.Connection.Open();
                cmd.CommandText = "usp_DeleteRepeaterRec";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@id", userid);
                cmd.ExecuteNonQuery();
                conn.Close();
                BindRepeater();
                Response.Write("Record Deleted SuccessFully!");
            }
            //Code For Insert Record
            //On Commad Name Supplied to the Link Button-- "Insert" Button
            if (e.CommandName == "Insert")
            {
                TextBox txtUname = (TextBox)e.Item.FindControl("txtftrname");
                TextBox txtUusername = (TextBox)e.Item.FindControl("txtftrusername");
                TextBox txtUPassword = (TextBox)e.Item.FindControl("txtftrpassword");
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.Connection.Open();
                cmd.CommandText = "usp_RepeaterDemo";
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name", txtUname.Text);
                cmd.Parameters.AddWithValue("@username", txtUusername.Text);
                cmd.Parameters.AddWithValue("@password", txtUPassword.Text);
                Response.Write("Record Inserted Successfully!");
                cmd.ExecuteNonQuery();
                cmd.Connection.Close();
                BindRepeater();
            }
        }
        //Cancel Button
        protected void btncancel_Click(object sender, EventArgs e)
        {
            //clear Text From Textboxes
            clearcontrol();
            btnsave.Text = "Save";
        }
    }
}
In above Code, BindRepeater() method is used to bind data into database and clearcontrol() method used to Clear Text From textboxes and ”OnItemCommand” for  Insert,Edit Delete Operation. 

OutPut:


Saturday 1 March 2014

insert edit update delete using web service in asp .net C#

Hello Friends !!
Web services are Web-based applications accessed using the protocols of the web to be used by the web applications. It is basically a class consisting of method that could use by other applications. In simple word it is a part of web application that provides facility to communicate one system to another system through http (Hyper Text Transfer Protocol).

In this post I will explain insert ,edit ,update and delete operation through web service in asp.net c#.Now I have described how to insert,edit,update and delete operation with the help of web service and using with linq to sql.Complete step are given below.

1.Open Visual Studio
2.Create a new Project (ASP.NET Web Service) name it (WebServiceCrudOpe).
When open “ASP.NET Web Service”.By Default some code are prewritten in Service1.cs page as shown in below image.


Here I am using linq to sql for the CRUD Operation by web service.
For the crud operation ,first I create a table as shown in below figure.


Next step is to add a new item “LINQ to SQL Classes”.
See below figure after drag and drop table.


Now next step is create method for Insert,Edit,Update and Delete operation in Service1.asmx.cs page
Service1.asmx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.Linq;
namespace WebServiceCrudOpe
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
        //Method for Insertind data into database
        [WebMethod]
        public dsh_webserviceCRUD InserData(dsh_webserviceCRUD obj)
        {
            dsh_webserviceCRUD webobj = new dsh_webserviceCRUD();
            webobj.Name = obj.Name;
            webobj.Address = obj.Address;
            webobj.ContactNo = obj.ContactNo;
            db.dsh_webserviceCRUDs.InsertOnSubmit(webobj);
            db.SubmitChanges();
            return webobj;
        }
        //Method for Read/Get data from database
        [WebMethod]
        public List<dsh_webserviceCRUD> ReadData()
        {
            List<dsh_webserviceCRUD> listdata = new List<dsh_webserviceCRUD>();
            listdata = (from o in db.dsh_webserviceCRUDs
                        select o).ToList();
            return listdata;
        }
        //Method for Get Specif ID from database
        [WebMethod]
        public List<dsh_webserviceCRUD> ReadSpecific(int id)
        {
            List<dsh_webserviceCRUD> listspecific = new List<dsh_webserviceCRUD>();
            listspecific = db.dsh_webserviceCRUDs.Where(o => o.Id == id).ToList();
            return listspecific;
        }
        //Method for Updating data of database
        [WebMethod]
        public dsh_webserviceCRUD UpdateRec(dsh_webserviceCRUD obj)
        {
            dsh_webserviceCRUD updatedata = new dsh_webserviceCRUD();
            updatedata = db.dsh_webserviceCRUDs.Where(o => o.Id == obj.Id).FirstOrDefault();
            updatedata.Name = obj.Name;
            updatedata.Address = obj.Address;
            updatedata.ContactNo = obj.ContactNo;

            db.SubmitChanges();
            return updatedata;
        }
        //Method for Deleting data of database
        [WebMethod]
        public dsh_webserviceCRUD DeleteRec(int id)
        {
            dsh_webserviceCRUD DelRec = new dsh_webserviceCRUD();
            DelRec = db.dsh_webserviceCRUDs.Where(o => o.Id.Equals(id)).FirstOrDefault();
            db.dsh_webserviceCRUDs.DeleteOnSubmit(DelRec);
            db.SubmitChanges();
            return DelRec;
        }
    }
}
Here “[WebMethod]” is responsible to execute code on web.
Now Run the Web Service .


After run webservice you get URL (http://localhost:58126/Service1.asmx) that shown in above figure.
Copy the URL for the further use.

Now Move to Make a client side Project for the use of Web Service.
3 .Open Visual Studio
4. Create a new Project (ASP.NET Web Application) name it (WebserviceCRUD).
After that I have design  Default.aspx page with three textbox ,one button and one GridView for CRUD operation.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebserviceCRUD._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width: 100%;
        }
        .style3
        {
            height: 41px;
        }
        .style4
        {
            height: 41px;
        }
        .style5
        {
            width: 38px;
            height: 41px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="height: 223px; width: 889px">
        <br />
        <table class="style1">
            <tr>
                <td class="style5">
                    Name:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox1" runat="server" Height="20px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style5">
                    Address:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style5">
                    ContactNo:
                </td>
                <td class="style4">
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3" colspan="2">
                 <asp:Button ID="Button1" runat="server" Text="Submit" OnClick="Button1_Click" Height="33px"
                        Width="76px" />
        <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
                </td>
            </tr>
        </table>
        <br />
        <br />
       
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" OnRowCommand="GridView1_RowCommand"
        DataKeyNames="Id" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting">
        <Columns>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("Name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Address">
                <ItemTemplate>
                    <asp:Label ID="lbladdress" runat="server" Text='<%#Eval("Address") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="ContactNO">
                <ItemTemplate>
                    <asp:Label ID="lblcontactno" runat="server" Text='<%#Eval("ContactNo") %>'> </asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <ItemTemplate>
                    <asp:ImageButton ID="editbtn" runat="server" Height="40px" ImageUrl="~/img/edit-128.png"
                        Width="44px" CommandName="edit" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:ImageButton ID="deletebtn" runat="server" ImageUrl="img/delete-24.png" Height="42px"
                        Width="39px" CommandName="delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>
Next step to add web service reference in project. Right click on project and select “Add Web Reference” as shown in below figure.


After select “Add Web Reference” you will get a window . In “Add Web Reference”window ,paste  URL (Which I copy in above scenario) within URL Textbox.Then Click on Go button,and see all available Web Service Method will appear on pane below.
Note give the specific “Web reference name “.I am using “localhost1”.


After click on “Add Reference” button, you can see  solution explorer, you will find “localhost1” is added in solution as shown in below figure.


After open  Default.aspx.cs and write following code.
Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebserviceCRUD.localhost1;
using System.Data.Linq;
namespace WebserviceCRUD
{
    public partial class _Default : System.Web.UI.Page
    {
        localhost1.Service1 svobj = new Service1();
        static int pk_id;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GrdBind();
            }
        }
        private void GrdBind()
        {
            List<dsh_webserviceCRUD> listdata1 = svobj.ReadData().ToList();
            GridView1.DataSource = listdata1;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Button1.Text == "Submit")
            {
                dsh_webserviceCRUD data = svobj.InserData(GetControlData());
                if (data != null)
                {
                    Label1.Text = data.Name + "Record" + " " + "Submited Succesfully";
                    Label1.Visible = true;
                    GrdBind();
                    ClearControl();
                }
            }
            else if (Button1.Text == "Update")
            {
                dsh_webserviceCRUD data1 = svobj.UpdateRec(GetControlData());
                Button1.Text = "Submit";
                GrdBind();
                ClearControl();
                Label1.Text = data1.Name + "" + "Record Updated Successfully";
                Label1.Visible = true;
            }
        }
        private void ClearControl()
        {
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
            TextBox3.Text = string.Empty;
        }
        private dsh_webserviceCRUD GetControlData()
        {
            dsh_webserviceCRUD cntrlobj = new dsh_webserviceCRUD();
            cntrlobj.Name = TextBox1.Text;
            cntrlobj.Address = TextBox2.Text;
            cntrlobj.ContactNo = TextBox3.Text;
            cntrlobj.Id = pk_id;
            return cntrlobj;
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
            pk_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
            if (e.CommandName == "edit")
            {
                List<dsh_webserviceCRUD> data = svobj.ReadSpecific(pk_id).ToList();
                TextBox1.Text = data.ToList()[0].Name;
                TextBox2.Text = data.ToList()[0].Address;
                TextBox3.Text = data.ToList()[0].ContactNo;
                Button1.Text = "Update";
                Label1.Visible = false;
            }
            else if (e.CommandName == "delete")
            {
                dsh_webserviceCRUD dlrec = svobj.DeleteRec(pk_id);
                Label1.Text = dlrec.Name + "  " + "Record Deleted Successfully";
                Label1.Visible = true;
                GrdBind();
            }
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
        }
    }
}
Run the application and see the output as below.


Popular Posts

Recent Posts

Sample Text

Stats

Powered by Blogger.

Popular Posts

Popular Posts

Join US on Facebook