Thursday 27 February 2014

Insert Edit Update Delete using wcf service in asp.net c#

Hello Friends !!
In this Post I will Explain WCF Service (Window Communication Foundation) in Asp .net c#.
In this post I will show you how to create WCF Service and how to consume it within an aspx page to perform CRUD operation using  WCF Service.For the CRUD (Create,Read,Update,Delete) operation using WCF service in asp with C#, I have use the one Stored procedure using in linq to sql.

First I have created one table in database :-


After creating table I have make one stored procedure with multiple queries when I execute this stored procedure using linq to sql it will give different result on condition to perform CRUD operation.
Here I am using also Resource file for set condition on stored procedure.
In the below stored procedure you can see parameter @Dboperation that condition value set by resource file.

CREATE PROCEDURE [dbo].[usp_WCF_CRUD]
@Dboperation varchar(50),
@empid int,
@name nvarchar(50),
@department nvarchar(50),
@desigination nvarchar(50),
@salary nvarchar(50),
@address nvarchar(50),
@contactno nvarchar(50),
AS
BEGIN
begin try
if(@Dboperation='ReadAll')
begin
select * from dsh_WCF_CRUD
end
else if(@Dboperation='ReadSpecific')
begin
select * from dsh_WCF_CRUD where empid=@empid
end
else if(@Dboperation='Create')
begin
INSERT INTO [Demo].[dbo].[dsh_WCF_CRUD]
           ([name],[department],[desigination],[salary],[address],[contactno])
VALUES
           (@name,@department,@desigination,@salary,@address,@contactno)
select * from dsh_WCF_CRUD where empid=scope_identity();
end
else if(@Dboperation='Update')
begin
UPDATE [Demo].[dbo].[dsh_WCF_CRUD]
    SET [name] = @name,
      [department] = @department,
     [desigination] = @desigination,
      [salary] =@salary,
      [address] = @address,
      [contactno] =@contactno
    WHERE empid=@empid
end
else if(@Dboperation='Delete')
begin
DELETE FROM [Demo].[dbo].[dsh_WCF_CRUD]
    WHERE empid=@empid
end
end try
begin catch
end catch
END
After Creating Stored Procedure 
1 Open Visual Studio 
2 Create a new Project (ASP.NET Web Application) name it (DataEntity)
3  Next step is to add a new item “LINQ to SQL Classes”.
   See figure below after drag and drop stored procedure.



After that ,
4 Add New Project (ASP.NET Web Application)  name it(ReasourceFile)
5 next step is to add a new item “Resources File”. Name it(Dboperation.resx).
Add the following value in resource file  in from the below figure.
This resource file use for database operation to set value into stored procedure.


Then after
6 Add New Project  (WCF Service Application) name it (WCF-CRUD)
Once you created project you will get default class files including Service.cs and IService.cs. But I am adding one new wcf service. 
7 next step is to add a new item “WCF Service”. Name it (empservice.svc).
After adding all this ,the whole solution look like in the below figure.


Now open Iempservice.cs and write following code.
Iempservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DataEntity;
namespace WCF_CRUD
{
    // NOTE: If you change the interface name "Iempservice" here, you must also update the reference to "Iempservice" in Web.config.
    [ServiceContract]
    public interface Iempservice
    {
        [OperationContract]
        void DoWork();
        [OperationContract]
        List<usp_WCF_CRUDResult> InsertEmployee(usp_WCF_CRUDResult empobj);
        [OperationContract]
        List<usp_WCF_CRUDResult> ReadAllEmployee();
        [OperationContract]
        List<usp_WCF_CRUDResult> ReadSpecific(int ID);
        [OperationContract]
        List<usp_WCF_CRUDResult> UpdateEmployee(usp_WCF_CRUDResult updateemp);
        [OperationContract]
        List<usp_WCF_CRUDResult> DeleteEmployee(int ID);
    }
}
After that open empservice.cs and write the following code.
empservice.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using DataEntity;
using System.Data.Linq;
using System.Data.SqlClient;
using ReasourceFile;

namespace WCF_CRUD
{
    // NOTE: If you change the class name "empservice" here, you must also update the reference to "empservice" in Web.config.
    public class empservice : Iempservice
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        public void DoWork()
        {
        }
        #region Iempservice Members
        List<usp_WCF_CRUDResult> Iempservice.InsertEmployee(usp_WCF_CRUDResult empobj)
        {
            List<DataEntity.usp_WCF_CRUDResult> empdata = new List<DataEntity.usp_WCF_CRUDResult>();
         
                using (DataClasses1DataContext db = new DataClasses1DataContext())
                {
                    empdata = db.usp_WCF_CRUD(Dboperation.CreateRecord, null, empobj.name, empobj.department, empobj.desigination, empobj.salary, empobj.address, empobj.contactno, null).ToList();
                }
               
            return empdata;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> ReadAllEmployee()
        {
            List<usp_WCF_CRUDResult> EmplList = new List<usp_WCF_CRUDResult>();
         
                using (DataClasses1DataContext db = new DataClasses1DataContext())
                {
                    EmplList = db.usp_WCF_CRUD(Dboperation.ReadAllRecord, null, null, null, null, null, null, null, null).ToList();
                }
         
         
            return EmplList;
        }
        #endregion
        #region Iempservice Members
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> ReadSpecific(int ID)
        {
            List<usp_WCF_CRUDResult> empobj = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                empobj = db.usp_WCF_CRUD(Dboperation.ReadSpecificRecord, ID, null, null, null, null, null, null, null).ToList();
            }
            return empobj;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> UpdateEmployee(usp_WCF_CRUDResult updateemp)
        {
            List<usp_WCF_CRUDResult> empobj = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                empobj = db.usp_WCF_CRUD(Dboperation.UpdateRecord,updateemp.empid,updateemp.name,updateemp.department,updateemp.desigination,updateemp.salary,updateemp.address,updateemp.contactno,null).ToList();
            }
            return empobj;
        }
        #endregion
        #region Iempservice Members

        public List<usp_WCF_CRUDResult> DeleteEmployee(int ID)
        {
            List<usp_WCF_CRUDResult> deleteemp = new List<usp_WCF_CRUDResult>();
            using (DataClasses1DataContext db = new DataClasses1DataContext())
            {
                deleteemp = db.usp_WCF_CRUD(Dboperation.DeleteRecord, ID, null, null, null, null, null, null, null).ToList();
            }
            return deleteemp;
        }
        #endregion
    }
}
Now copy connection string from DataEntity config file to WCF-CRUD config file.
See below figure.



After that Add Client side Project.
8 Add New Project (ASP.NET Web Application)  name it(ClientApp)
After adding project the whole solution look like below figure.


After that open ClienApp Project and open Default.aspx and design Default.aspx as I done in following code.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ClientApp._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
        {
        }
        .style3
        {
            width: 94px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td colspan="2">
                    Register
                </td>
            </tr>
            <tr>
                <td class="style3">
                    EmployeeName:
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Desigination:
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Department:
                </td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Salary:
                </td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    Address:
                </td>
                <td>
                    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style3">
                    ContactNo:
                </td>
                <td>
                    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2" colspan="2">
                    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
                    &nbsp;
                    <asp:Label ID="Label1" runat="server" ForeColor="Red" Text="Data is not available"
                        Visible="False"></asp:Label>
                </td>
            </tr>
        </table>
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="White"
        BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4" OnRowCommand="GridView1_RowCommand"
        DataKeyNames="empid" OnRowDeleting="GridView1_RowDeleting" OnRowEditing="GridView1_RowEditing">
        <RowStyle BackColor="White" ForeColor="#003399" />
        <Columns>
            <asp:TemplateField HeaderText="EmpId" Visible="false">
                <ItemTemplate>
                    <asp:Label ID="lblempid" runat="server" Text='<%#Eval("empid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="EmpName">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%#Eval("name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department">
                <ItemTemplate>
                    <asp:Label ID="lbldepartment" runat="server" Text='<%#Eval("department") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Desigination">
                <ItemTemplate>
                    <asp:Label ID="lbldesigination" runat="server" Text='<%#Eval("desigination") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="salary">
                <ItemTemplate>
                    <asp:Label ID="lblsalary" runat="server" Text='<%#Eval("salary") %>'></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="EditImage" runat="server" CommandName="Edit" ImageUrl="img/editimage.jpg"
                        Height="33px" Width="36px" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:ImageButton ID="ImageButton1" runat="server" Height="31px" CommandName="Delete"
                        ImageUrl="~/img/images (1).jpg" Width="36px" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
    </asp:GridView>
    </form>
</body>
</html>
Default.aspx look like below figure.



After that move to WCF-CUD project and run empservice.svc .



after run service you get web service url (http://localhost:49994/empservice.svc) that show in below figure.


Now move to ClienApp project ,right click on project and select  “Add Service Reference” from context menu.


After enter your service url and click on GO button to see a list of available services and all the available web method (service method) will appear on the pane below.
Note give the specific reference name. I am using default service reference namespace as “ServiceReference1”.


Now observ the solution explorer, you will find ServiceReference1 is added in solution.


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 System.ServiceModel;
using System.Data.Linq;
using DataEntity;
using ReasourceFile;
using WCF_CRUD;
using ClientApp.ServiceReference1;
namespace ClientApp
{
    public partial class _Default : System.Web.UI.Page
    {
        static int PK_id;
        ServiceReference1.IempserviceClient ss1 = new ServiceReference1.IempserviceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List<usp_WCF_CRUDResult> empdata = ss1.ReadAllEmployee();
            GridView1.DataSource = empdata;
            GridView1.DataBind();
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            if (Button1.Text == "Update")
            {
                List<usp_WCF_CRUDResult> emplist1 = ss1.UpdateEmployee(GetControlData());
            }
            else
            {
                List<usp_WCF_CRUDResult> emplist = ss1.InsertEmployee(GetControlData());
            }
            BindGrid();
            ClearControl();
        }
        private void ClearControl()
        {
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
            TextBox3.Text = string.Empty;
            TextBox4.Text = string.Empty;
            TextBox5.Text = string.Empty;
            TextBox6.Text = string.Empty;
        }
        private usp_WCF_CRUDResult GetControlData()
        {
            usp_WCF_CRUDResult uspobj = new usp_WCF_CRUDResult()
            {
                name = TextBox1.Text,
                department = TextBox2.Text,
                desigination = TextBox3.Text,
                salary = TextBox4.Text,
                address = TextBox5.Text,
                contactno = TextBox6.Text,
                empid = PK_id
            };
            return uspobj;
        }
        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (GridView1.Rows.Count == 0)
            {
                Label1.Visible = true;
            }
            else
            {
                if (e.CommandName == "Edit")
                {
                    GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                    PK_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
                    List<usp_WCF_CRUDResult> emplist = ss1.ReadSpecific(PK_id);
                    TextBox1.Text = emplist[0].name;
                    TextBox2.Text = emplist[0].department;
                    TextBox3.Text = emplist[0].desigination;
                    TextBox4.Text = emplist[0].salary;
                    TextBox5.Text = emplist[0].address;
                    TextBox6.Text = emplist[0].contactno;
                    Button1.Text = "Update";
                }
                else if (e.CommandName == "Delete")
                {
                    GridViewRow index = (GridViewRow)((ImageButton)e.CommandSource).NamingContainer;
                    PK_id = Convert.ToInt32(GridView1.DataKeys[index.RowIndex].Value);
                    List<usp_WCF_CRUDResult> deleteemp = ss1.DeleteEmployee(PK_id);
                    BindGrid();
                }
            }
        }
        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.










Saturday 22 February 2014

Insert,Edit,Update and Delete Using LINQ to SQL in Asp .Net C#

Hello Friends !!
In this Post I will Explain Create,Edit,Update,Delete  Or  we can say CRUD Operation using LINQ  to SQL in Asp .net c#.
For This Operation I have created One table name as dsh_linqCRUD  in Database with empid , name, desigination, department, salary, address, contactno where empid is auto increament.
 See dsh_linqCRUD  in Database:-


Aftet Create table ” dsh_linqCRUD”  
1  Open Visual Studio
2  Create a new Project(ASP.NET Web Application)
     name it (CRUDinLinq)
3 next step is to add a new item “LINQ to SQL Classes”.



See below figure after add LINQ to SQL Classes.


Aftre then go to “Server Explorer” window and create a new connection to the database  then drag and drop the table “dsh_linqCRUD”  .
See below figure after drop table.



After then design the aspx page (Default.aspx)
In this aspx page I have use the six textbox and two button and one GridView Data control to view,edit,update,and delete data.

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CRUDinLinq._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: 452px;
            text-align: right;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table class="style1">
            <tr>
                <td colspan="2" style="text-align: center">
                    Register
                </td>
            </tr>
            <tr>
                <td class="style2">
                    EmployeeName:
                </td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Desigination:
                </td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Style="margin-left: 0px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Department:
                </td>
                <td>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Salary:
                </td>
                <td>
                    <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    Address:
                </td>
                <td>
                    <asp:TextBox ID="TextBox5" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td class="style2">
                    ContactNo:
                </td>
                <td>
                    <asp:TextBox ID="TextBox6" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2" style="margin-left: 40px">
                 
                    <asp:Button ID="btnsubmit" runat="server" Text="Submit" OnClick="btnsubmit_Click" />
                    &nbsp;<asp:Button ID="btncancel" runat="server" Text="Cancel" OnClick="btncancel_Click"
                        Visible="False" />
                </td>
            </tr>
        </table>
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowEditing="GridView1_RowEditing"
        OnRowDeleting="GridView1_RowDeleting" CellPadding="4" ForeColor="#333333" GridLines="None"
        Style="text-align: center">
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <Columns>
            <asp:TemplateField HeaderText="EmpId" Visible="false">
                <ItemTemplate>
                    <asp:Label ID="lblempid" runat="server" Text='<%#Eval("empid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Name">
                <ItemTemplate>
                    <asp:Label ID="lblname" runat="server" Text='<%# Eval("name") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Desigination">
                <ItemTemplate>
                    <asp:Label ID="lbldesigination" runat="server" Text='<%#Eval("desigination") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Department">
                <ItemTemplate>
                    <asp:Label ID="lbldepartment" runat="server" Text='<%#Eval("department") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Salary">
                <ItemTemplate>
                    <asp:Label ID="lblsalary" runat="server" Text='<%#Eval("salary") %>'>
                    </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:Button ID="btnedit" runat="server" CommandName="Edit" Text="Edit" CommandArgument='<%# Eval("empid") %>'
                        OnClientClick="return confirm(‘Are you sure?’)" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:Button ID="btndelete" runat="server" CommandName="Delete" Text="Delete" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#999999" />
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
    </asp:GridView>
    </form>
</body>
</html>

C# code of 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.Linq;
using System.Data;
using System.Data.SqlClient;
namespace CRUDinLinq
{
    public partial class _Default : System.Web.UI.Page
    {
        DataClasses1DataContext db = new DataClasses1DataContext();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
        private void BindGrid()
        {
            List<dsh_linqCRUD> empdata = (from o in db.dsh_linqCRUDs
                                          select o).ToList();
            GridView1.DataSource = empdata;
            GridView1.DataBind();
        }
        protected void btnsubmit_Click(object sender, EventArgs e)
        {
            if (btnsubmit.Text == "Submit")
            {
                dsh_linqCRUD lqobj = new dsh_linqCRUD();
                lqobj.name = TextBox1.Text;
                lqobj.desigination = TextBox2.Text;
                lqobj.department = TextBox3.Text;
                lqobj.salary = TextBox4.Text;
                lqobj.address = TextBox5.Text;
                lqobj.contactno = TextBox6.Text;
                db.dsh_linqCRUDs.InsertOnSubmit(lqobj);
                db.SubmitChanges();
                BindGrid();
            }
            else
            {
                var id = ViewState["empiid1"].ToString();
                var data = (from o in db.dsh_linqCRUDs
                            where o.empid == Convert.ToInt32(id)
                            select o).Single();
                data.name = TextBox1.Text;
                data.desigination = TextBox2.Text;
                data.department = TextBox3.Text;
                data.salary = TextBox4.Text;
                data.address = TextBox5.Text;
                data.contactno = TextBox6.Text;
                db.SubmitChanges();
                BindGrid();
                btnsubmit.Text = "Submit";
                btncancel.Visible = false;
            }
            Clearcontrol();
        }
        private void Clearcontrol()
        {
            TextBox1.Text = string.Empty;
            TextBox2.Text = string.Empty;
            TextBox3.Text = string.Empty;
            TextBox4.Text = string.Empty;
            TextBox5.Text = string.Empty;
            TextBox6.Text = string.Empty;
        }
        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            Label lblempid = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lblempid");
            var id = Convert.ToInt32(lblempid.Text);
            ViewState["empiid1"] = id;
            Label lblname = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lblname");
            Label lbldesigination = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lbldesigination");
            Label lbldepartment = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lbldepartment");
            Label lblsalary = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lblsalary");
            Label lbladdress = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lbladdress");
            Label lblcontactno = (Label)GridView1.Rows[e.NewEditIndex].FindControl("lblcontactno");
            TextBox1.Text = lblname.Text;
            TextBox2.Text = lbldesigination.Text;
            TextBox3.Text = lbldepartment.Text;
            TextBox4.Text = lblsalary.Text;
            TextBox5.Text = lbladdress.Text;
            TextBox6.Text = lblcontactno.Text;
            btnsubmit.Text = "Update";
            btncancel.Visible = true;
        }
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Label lblempid = (Label)GridView1.Rows[e.RowIndex].FindControl("lblempid");
            var id = Convert.ToInt32(lblempid.Text);
            var data = (from o in db.dsh_linqCRUDs
                        where o.empid == Convert.ToInt32(id)
                        select o).Single();
            db.dsh_linqCRUDs.DeleteOnSubmit(data);
            db.SubmitChanges();
            BindGrid();
        }
        protected void btncancel_Click(object sender, EventArgs e)
        {
            Clearcontrol();
            btnsubmit.Text = "Submit";
            btncancel.Visible = false;
        }
    }
}
Run the application and see the output as below.






Friday 14 February 2014

Import And Upload Excel File data into Gridview in Asp.net Usiing C#

Hello Friends!!
In this post I will Explain Import And Upload Excel or we can can Display Excel file data into GridView
In Asp .net Using C#.
I am importing/uploading  an excel file data into a gridview. I have one fileupload control where I need to select an excel file and I have a gridview to show the excel file data and a button where need to click after choosing one excel file so that I can show my excel file data into gridview in asp.net c#.
1  Open Visual Studio
2  Create a new Project(ASP.NET Web Application)
 name it (ImportExcelData)

The whole solution look like in the below image.


To Implement This concept I need to make Excel file that shown in below.


After The Creation Of Excel File ,write the following code in Default.aspx page.
Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ImportExcelData._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>
    <script type="text/javascript">
        function Check(sender, args) {
          var fileextension =
           if (fileextension == ".xlsx")
           {
            alert('Select only Xlsx file');
           }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server" />
            <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        </div>
        <div>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
                <ContentTemplate>
                    <asp:GridView ID="Gridview1" runat="server" AutoGenerateColumns="false">
                        <Columns>
                            <asp:BoundField DataField="Name" HeaderStyle-BackColor="Chocolate" HeaderText="Name"
                                ApplyFormatInEditMode="true" ShowHeader="true" NullDisplayText="Null" />
                            <asp:BoundField DataField="Address" HeaderStyle-BackColor="Chocolate" HeaderText="Address"
                                ShowHeader="true" />
                            <asp:BoundField DataField="Salary" HeaderStyle-BackColor="Chocolate" HeaderText="Salary"
                                ShowHeader="true" />
                        </Columns>
                    </asp:GridView>
                </ContentTemplate>
            </asp:UpdatePanel>
            <asp:Button runat="server" ID="BtnUpload" OnClick="BtnUpload_OnClick" Text="Upload" />
        </div>
    </div>
    </form>
</body>
</html>
C# code of Default.aspx.cs
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.IO;
using System.Data.OleDb;
namespace ImportExcelData
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void BtnUpload_OnClick(object sender, EventArgs e)
        {
            Label1.Text = FileUpload1.PostedFile.FileName;
            if (FileUpload1.HasFile)
            {
                string connectionstring = "";
                string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string fileextension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string filelocation = Server.MapPath("~/file/") + filename;
                FileUpload1.SaveAs(filelocation);
                if (fileextension == ".xlsx")
                {
                    connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filelocation + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=2\"";
                    OleDbConnection conn = new OleDbConnection(connectionstring);
                    OleDbCommand cmd = new OleDbCommand();
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = "select * from [Sheet1$]";
                    cmd.Connection = conn;
                    OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
                    System.Data.DataTable dt = new System.Data.DataTable();
                    oda.Fill(dt);
                    Gridview1.DataSource = dt;
                    Gridview1.DataBind();
                }
            }
            else
            {
                BtnUpload.Attributes.Add("OnClientClick", "javascript:alert('Select Excel file');");
                Gridview1.DataSource = null;
                Gridview1.DataBind();
            }
            FileUpload1.Attributes.Clear();
        }
    }
}

Run the application and see the output as below.




Saturday 8 February 2014

Insert, Edit, Update, Delete data in Gridview and DataBinding DropDownList Inside GridView In ASP .NET Using C#

Hello, I will explain  Insert,Update,Edit,Delete operation in Gridview and also Bind DropDownList Inside GridView .

  1. Open Visual Studio
  2. Create a new Empty Web Site
  3. Add new item>WebForm>name it(GridOperation.aspx)

I have created one aspx page with One gridview control to insert,update,edit,delete data and DataBinding DropDownList.
I have three dropdown inside gridview for bind data Country,State,City . for bind country,state,city dropdownlist I need to populate state dropdown based on country dropdown and I need to populate region dropdown based on state dropdown for what I have created three table of country,state,city tables in sql server that shown in below.

County table> Name it dashrath_Country


 State table> Name it dashrath_State


City table> Name it dashrath_city

After design the aspx page.
HTML source of page  GridOperation.aspx
GridOperation.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridOperation.aspx.cs" Inherits="Default2" %>
<!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>
</head>
<body style="background-color: Silver">
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnPageIndexChanging="GridView1_PageIndexChanging"
            AllowPaging="True" BackColor="White" BorderColor="#999999" BorderStyle="None"
            BorderWidth="1px" CellPadding="3" GridLines="Vertical" OnRowCommand="GridView1_RowCommand"
            Caption="GRIDVIEW EXAMPLE" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDataBound="GridView1_RowDataBound"
            OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" Height="348px"
            ShowFooter="True" Width="767px">
            <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
            <Columns>
                <asp:TemplateField HeaderText="EMP_ID" Visible="false">
                    <ItemTemplate>
                        <asp:Label ID="lblemp_id" runat="server" Text='<%#Eval("emp_id") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:Label ID="lbl_edit" runat="server" Text='<%# Eval("emp_id") %>'></asp:Label>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="FirstName">
                    <ItemTemplate>
                        <asp:Label ID="lblfname" runat="server" Text='<%#Eval("fname") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_fname" runat="server" Text='<%# Eval("fname") %>'></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="txt_fname"
                            ErrorMessage="*" ValidationGroup="update1"></asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtf_fname" runat="server" Width="128px"></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator20" runat="server" ControlToValidate="txtf_fname"
                            ErrorMessage="*" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="LastName">
                    <ItemTemplate>
                        <asp:Label ID="lblname" runat="server" Text='<%#Eval("lname") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_lname" runat="server" Text='<%# Eval("lname") %>'></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator10" runat="server" ControlToValidate="txt_lname"
                            ErrorMessage="*" ValidationGroup="update1"></asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtf_lname" runat="server"></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtf_lname"
                            ErrorMessage="*" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Address">
                    <ItemTemplate>
                        <asp:Label ID="lbladdress" runat="server" Text='<%#Eval("address") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_address" runat="server" Text='<%# Eval("address") %>'></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator11" runat="server" ControlToValidate="txt_address"
                            ErrorMessage="*" ValidationGroup="update1"></asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtf_address" runat="server"></asp:TextBox>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="txtf_address"
                            ErrorMessage="*" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField Visible="false">
                    <ItemTemplate>
                        <asp:Label ID="lblcon" runat="server" Text='<%#Eval("country1") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country">
                    <ItemTemplate>
                        <asp:Label ID="lblcountry" runat="server" Text='<%#Eval("country") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="drp_country" runat="server" OnSelectedIndexChanged="drp_country_SelectedIndexChanged"
                            AutoPostBack="true">
                        </asp:DropDownList>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator12" runat="server" ControlToValidate="drp_country"
                            ErrorMessage="*" InitialValue="0" ValidationGroup="update1"></asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="footer_country" runat="server" AutoPostBack="True" OnSelectedIndexChanged="footer_country_SelectedIndexChanged">
                        </asp:DropDownList>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="footer_country"
                            ErrorMessage="*" InitialValue="0" ValidationGroup="submit"></asp:RequiredFieldValidator>
                        &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator15" runat="server" ControlToValidate="footer_country"
                            ErrorMessage="*" InitialValue="0" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField Visible="false">
                    <ItemTemplate>
                        <asp:Label ID="lblstcon" runat="server" Text='<%#Eval("state1") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:Label ID="lblcity" runat="server" Text='<%#Eval("city") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:DropDownList ID="drp_city" runat="server" AutoPostBack="true">
                        </asp:DropDownList>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator14" runat="server" ControlToValidate="drp_city"
                            ErrorMessage="*" ValidationGroup="update1"></asp:RequiredFieldValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="footer_city" runat="server">
                        </asp:DropDownList>
                        &nbsp;
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ControlToValidate="footer_city"
                            ErrorMessage="*" InitialValue="0" ValidationGroup="submit"></asp:RequiredFieldValidator>
                        &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator17" runat="server" ControlToValidate="footer_city"
                            ErrorMessage="*" InitialValue="0" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactNo">
                    <ItemTemplate>
                        <asp:Label ID="lblcontactno" runat="server" Text='<%#Eval("contactno") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_contactno" runat="server" Text='<%# Eval("contactno") %>'></asp:TextBox>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txt_contactno"
                            ErrorMessage="*" ValidationExpression="\d{10}" ValidationGroup="update1"></asp:RegularExpressionValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtf_contactno" runat="server"></asp:TextBox>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtf_contactno"
                            ErrorMessage="*" ValidationExpression="\d{10}" ValidationGroup="submit"></asp:RegularExpressionValidator>
                        &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator18" runat="server" ControlToValidate="txtf_contactno"
                            ErrorMessage="*" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Email_ID">
                    <ItemTemplate>
                        <asp:Label ID="lblemailid" runat="server" Text='<%#Eval("emailid") %>'></asp:Label>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txt_id" runat="server" Text='<%# Eval("emailid") %>'></asp:TextBox>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txt_id"
                            ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            ValidationGroup="update1"></asp:RegularExpressionValidator>
                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtf_emailid" runat="server"></asp:TextBox>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator3" runat="server" ControlToValidate="txtf_emailid"
                            ErrorMessage="*" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
                            ValidationGroup="submit"></asp:RegularExpressionValidator>
                        &nbsp;<asp:RequiredFieldValidator ID="RequiredFieldValidator19" runat="server" ControlToValidate="txtf_emailid"
                            ErrorMessage="*" ValidationGroup="submit"></asp:RequiredFieldValidator>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton2" runat="server" CommandName="deleteitem" CommandArgument='<%# Eval("emp_id") %>'
                            CausesValidation="False">Delete</asp:LinkButton>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Button ID="btn_add" runat="server" Text="Insert" OnClick="btn_add_Click" ValidationGroup="submit" />
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit IN Gridview">
                    <ItemTemplate>
                        <asp:LinkButton ID="LinkButton3" runat="server" CommandName="edit" ValidationGroup="update">Edit</asp:LinkButton>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:LinkButton ID="LinkButton4" runat="server" CommandName="update" ValidationGroup="update1">update</asp:LinkButton>
                        &nbsp;<asp:LinkButton ID="LinkButton5" runat="server" CommandName="cancel">cencel</asp:LinkButton>
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
            <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
            <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
            <HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="#DCDCDC" />
        </asp:GridView>
    </div>
    <asp:Label ID="Label1" runat="server" Text="Label" Visible="False"></asp:Label>
    </form>
</body>
</html>
C# code of GridOperation.aspx.cs
GridOperation.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;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class Default2 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["city-state-country"].ConnectionString.ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bind();
            drpfooter_country();
        }
    }
    public void bind()
    {
        SqlCommand cmd = new SqlCommand("select e1.emp_id,e1.fname,e1.lname,e1.address,e1.country as country1, c1.country,e1.state as state1,e1.city as city1,s1.state,c2.city, e1.contactno,e1.emailid from dasharth_employee as e1,dashrath_Country as c1,dashrath_State as s1,dashrath_city as c2 where e1.country=c1.country_id and e1.state=s1.state_id and e1.city=c2.city_id order by e1.emp_id asc");
        cmd.Connection = con;
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adp.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
        {
            DropDownList ddlcountry = (DropDownList)e.Row.FindControl("drp_country");
            DropDownList ddlstate = (DropDownList)e.Row.FindControl("drp_state");
            DropDownList ddlcity = (DropDownList)e.Row.FindControl("drp_city");
            Label ddlcon = (Label)e.Row.FindControl("lblcon");
            Label ddlcon1 = (Label)e.Row.FindControl("lblstcon");
            Label ddlcon2 = (Label)e.Row.FindControl("lblcty");
            int con1 = Convert.ToInt32(ddlcon.Text);
            int con2 = Convert.ToInt32(ddlcon1.Text);
            DataTable dt = new DataTable();
            string sql = "select * From dashrath_Country";
            SqlDataAdapter da = new SqlDataAdapter(sql, con);
            da.Fill(dt);
            ddlcountry.DataSource = dt;
            ddlcountry.DataTextField = "country";
            ddlcountry.DataValueField = "country_id";
            ddlcountry.DataBind();
            ddlcountry.SelectedValue = ddlcon.Text;
            ddlcountry.Items.Insert(0, new ListItem("--Select--", "0"));
            ddlstate.Items.Insert(0, new ListItem("--select--", "0"));
       
            DataTable dt1 = new DataTable();
            string sql1 = "select * from dashrath_State where country_id='" + con1 + "'";
            SqlDataAdapter da1 = new SqlDataAdapter(sql1, con);
            da1.Fill(dt1);
            ddlstate.DataSource = dt1;
            ddlstate.DataTextField = "state";
            ddlstate.DataValueField = "state_id";
            ddlstate.DataBind();
            ddlstate.SelectedValue = ddlcon1.Text;
            DataTable dt2 = new DataTable();
            string sql2 = "select * from dashrath_city where state_id='" + con2 + "'";
            SqlDataAdapter da2 = new SqlDataAdapter(sql2, con);
            da2.Fill(dt2);
            ddlcity.DataSource = dt2;
            ddlcity.DataTextField = "city";
            ddlcity.DataValueField = "city_id";
            ddlcity.DataBind();
            ddlcity.SelectedValue = ddlcon2.Text;
        }
    }
    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        bind();
        drpfooter_country();
    }
    protected void drp_country_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList drpcon = (DropDownList)sender;
        GridViewRow gr = (GridViewRow)drpcon.NamingContainer;
        DropDownList ddcon = (DropDownList)gr.FindControl("drp_country");
        DropDownList ddst = (DropDownList)gr.FindControl("drp_state");
        DropDownList ddcct = (DropDownList)gr.FindControl("drp_city");
        DataTable dt = new DataTable();
        string sql = "select * from dashrath_State where country_id='" + ddcon.SelectedValue + "'";
        SqlDataAdapter adp = new SqlDataAdapter(sql, con);
        adp.Fill(dt);
        ddst.DataSource = dt;
        ddst.DataTextField = "state";
        ddst.DataValueField = "state_id";
        ddst.DataBind();
        ddst.Items.Insert(0, new ListItem("--select--", "0"));
        ddcct.Items.Clear();
        ddcct.Items.Insert(0, new ListItem("--select--", "0"));
    }
    protected void drp_state_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList drlst = (DropDownList)sender;
        GridViewRow grc = (GridViewRow)drlst.NamingContainer;
        DropDownList ddst = (DropDownList)grc.FindControl("drp_state");
        DropDownList drct = (DropDownList)grc.FindControl("drp_city");
        DataTable dt = new DataTable();
        string sql = "select * from dashrath_city where state_id='" + ddst.SelectedValue + "'";
        SqlDataAdapter adp = new SqlDataAdapter(sql, con);
        adp.Fill(dt);
        drct.DataSource = dt;
        drct.DataTextField = "city";
        drct.DataValueField = "city_id";
        drct.DataBind();
        drct.Items.Insert(0, new ListItem("--select--", "0"));
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        try
        {
            GridView1.EditIndex = e.NewEditIndex;
            bind();
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            drpfooter_country();
            con.Close();
        }
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "deleteitem")
        {
            int id2 = Convert.ToInt32(e.CommandArgument);
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.Connection.Open();
            cmd.CommandText = "usp_delete";
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@emp_id", id2);
            cmd.ExecuteNonQuery();
            cmd.Connection.Close();
            bind();
            drpfooter_country();
        }
    }
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.EditIndex = -1;
        GridView1.PageIndex = e.NewPageIndex;
        bind();
        drpfooter_country();
        Label1.Visible = false;
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Label id = ((Label)GridView1.Rows[e.RowIndex].FindControl("lbl_edit"));
        int id2 = Convert.ToInt32(id.Text);
        TextBox txfname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_fname");
        TextBox txlname = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_lname");
        TextBox txaddress = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_address");
        DropDownList drcountry = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("drp_country");
        DropDownList drstate = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("drp_state");
        DropDownList drcity = (DropDownList)GridView1.Rows[e.RowIndex].FindControl("drp_city");
        TextBox txcontactno = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_contactno");
        TextBox txemailid = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txt_id");
        SqlCommand cmd1 = new SqlCommand("update dasharth_employee set fname='" + txfname.Text + "',lname='" + txlname.Text + "',address='" + txaddress.Text + "',country='" + drcountry.SelectedValue + "',state='" + drstate.SelectedValue + "',city='" + drcity.SelectedValue + "',contactno='" + txcontactno.Text + "',emailid='" + txemailid.Text + "' where emp_id= " + id2, con);
        cmd1.Connection = con;
        cmd1.Connection.Open();
        cmd1.ExecuteNonQuery();
        cmd1.Connection.Close();
        GridView1.EditIndex = -1;
        bind();
        drpfooter_country();
        Label1.Text = txfname.Text + "" + "updated successfully";
        Label1.Visible = true;
    }
    public void drpfooter_country()
    {
        GridViewRow grd1 = (GridViewRow)GridView1.FooterRow;
        DropDownList drplstc = (DropDownList)grd1.FindControl("footer_country");
        DropDownList ddlstate = (DropDownList)grd1.FindControl("footer_state");
        DropDownList ddlcity = (DropDownList)grd1.FindControl("footer_city");
        DataTable dt = new DataTable();
        string sql = "select * From dashrath_Country";
        SqlDataAdapter da = new SqlDataAdapter(sql, con);
        da.Fill(dt);
        drplstc.DataSource = dt;
        drplstc.DataTextField = "country";
        drplstc.DataValueField = "country_id";
        drplstc.DataBind();
        drplstc.Items.Insert(0, new ListItem("--Select--", "0"));
        DataTable dt1 = new DataTable();
        string sql2 = "select * from dashrath_State ";
        SqlDataAdapter da1 = new SqlDataAdapter(sql2, con);
        da1.Fill(dt1);
        ddlstate.DataSource = dt1;
        ddlstate.DataTextField = "state";
        ddlstate.DataValueField = "state_id";
        ddlstate.DataBind();
        ddlstate.Items.Insert(0, new ListItem("--Select--", "0"));
        ddlcity.Items.Insert(0, new ListItem("--select--", "0"));
    }
    protected void footer_country_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList drpfoocon = (DropDownList)sender;
        GridViewRow gr = (GridViewRow)drpfoocon.NamingContainer;
        DropDownList ddconf_country = (DropDownList)gr.FindControl("footer_country");
        DropDownList ddstf_state = (DropDownList)gr.FindControl("footer_state");
        DropDownList ddfooter_ct = (DropDownList)gr.FindControl("footer_city");
        DataTable dt = new DataTable();
        string sql = "select * from dashrath_State where country_id='" + ddconf_country.SelectedValue + "'";
        SqlDataAdapter adp = new SqlDataAdapter(sql, con);
        adp.Fill(dt);
        ddstf_state.DataSource = dt;
        ddstf_state.DataTextField = "state";
        ddstf_state.DataValueField = "state_id";
        ddstf_state.DataBind();
        ddstf_state.Items.Insert(0, new ListItem("--select--", "0"));
        ddfooter_ct.Items.Clear();
        ddfooter_ct.Items.Insert(0, new ListItem("--select--", "0"));  
    }
    protected void footer_state_SelectedIndexChanged(object sender, EventArgs e)
    {
        DropDownList drrlst = (DropDownList)sender;
        GridViewRow grc = (GridViewRow)drrlst.NamingContainer;
        DropDownList ddfooter_st = (DropDownList)grc.FindControl("footer_state");
        DropDownList ddfooter_ct = (DropDownList)grc.FindControl("footer_city");
        DataTable dt = new DataTable();
        string sql = "select * from dashrath_city where state_id='" + ddfooter_st.SelectedValue + "'";
        SqlDataAdapter adp = new SqlDataAdapter(sql, con);
        adp.Fill(dt);
        ddfooter_ct.DataSource = dt;
        ddfooter_ct.DataTextField = "city";
        ddfooter_ct.DataValueField = "city_id";
        ddfooter_ct.DataBind();
        ddfooter_ct.Items.Insert(0, new ListItem("--select--", "0"));
    }
    protected void btn_add_Click(object sender, EventArgs e)
    {
        GridViewRow grd = (GridViewRow)GridView1.FooterRow;
        TextBox txtfname_foo = (TextBox)grd.FindControl("txtf_fname");
        TextBox txtlname_foo = (TextBox)grd.FindControl("txtf_lname");
        TextBox txtaddress_foo = (TextBox)grd.FindControl("txtf_address");
        DropDownList ddrcountry_foo = (DropDownList)grd.FindControl("footer_country");
        DropDownList ddrstate_foo = (DropDownList)grd.FindControl("footer_state");
        DropDownList ddrcity_foo = (DropDownList)grd.FindControl("footer_city");
        TextBox txtcontact_foo = (TextBox)grd.FindControl("txtf_contactno");
        TextBox txtemail_foo = (TextBox)grd.FindControl("txtf_emailid");
        SqlDataAdapter da = new SqlDataAdapter("select fname,lname from dasharth_employee where fname='" + txtfname_foo.Text + "' and lname='" + txtlname_foo.Text + "' ", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        if (ds.Tables[0].Rows.Count > 0)
        {
            Label1.Text = txtfname_foo.Text + "" + "Already Exist..Try Another Name";
            Label1.Visible = true;
            txtfname_foo.Text = "";
            txtlname_foo.Text = "";
            txtaddress_foo.Text = "";
            txtcontact_foo.Text = "";
            txtemail_foo.Text = "";
        }
        else
        {
            SqlCommand cmd = new SqlCommand("insert into dasharth_employee(fname,lname,address,country,state,city,contactno,emailid) values('" + txtfname_foo.Text + "','" + txtlname_foo.Text + "','" + txtaddress_foo.Text + "','" + ddrcountry_foo.SelectedValue + "','" + ddrstate_foo.SelectedValue + "','" + ddrcity_foo.SelectedValue + "','" + txtcontact_foo.Text + "','" + txtemail_foo.Text + "') ", con);
            cmd.Connection = con;
            cmd.Connection.Open();
            cmd.ExecuteNonQuery();
            con.Close();
            bind();
            Label1.Text = txtfname_foo.Text + "" + "inserted succesfully";
            Label1.Visible = true;
            drpfooter_country();
        }
    }
}
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