Monday, 30 December 2013

Shopping Cart Example code

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <script type="text/javascript">
        function GetAmount()
        {
            var qty = document.getElementById('<%= txtQuantity.ClientID %>').value;
            var Price = document.getElementById('<%= txtPrice.ClientID %>').value;
            var Amount = (qty * Price);
            document.getElementById('<%= txtAmount.ClientID %>').value = Amount;
        }
    </script>
    <div>
        <asp:Label ID="lblMsg" runat="server"></asp:Label>
        <div>
            <div>
                Bill No:
            </div>
            <div>
                <asp:TextBox ID="txtBillNo" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvBillNo" runat="server" ValidationGroup="Customer"
                    ControlToValidate="txtBillNo" ErrorMessage="<b>please enter bill no</b>">
                </asp:RequiredFieldValidator>
            </div>
            <div>
                Customer Name:
            </div>
            <div>
                <asp:TextBox ID="txtCustomerName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvCustomerName" runat="server" ValidationGroup="Customer"
                    ControlToValidate="txtCustomerName" ErrorMessage="<b>please enter CustomerName</b>">
                </asp:RequiredFieldValidator>
            </div>
            <div>
                Address:
            </div>
            <div>
                <asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvAddress" runat="server" ValidationGroup="Customer"
                    ControlToValidate="txtAddress" ErrorMessage="<b>please enter Address</b>">
                </asp:RequiredFieldValidator>
            </div>
            <div>
                Gender:
            </div>
            <div>
                <asp:RadioButtonList ID="rblGender" runat="server">
                    <asp:ListItem Value="Male">Male</asp:ListItem>
                    <asp:ListItem Value="Female">Female</asp:ListItem>
                </asp:RadioButtonList>
            </div>
        </div>
        <div style="border: 1px solid gray; height: 200px; padding: 5px">
            <div style="width: 155px; float: left;">
                <div>
                    Product Name:
                </div>
                <div>
                    <asp:TextBox ID="txtProductName" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvProductName" runat="server" ValidationGroup="Product"
                        ControlToValidate="txtProductName" ErrorMessage="<b>please enter product</b>">
                    </asp:RequiredFieldValidator>
                </div>
            </div>
            <div style="width: 155px; float: left;">
                <div>
                    Quantity:
                </div>
                <div>
                    <asp:TextBox ID="txtQuantity" runat="server"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvQuantity" runat="server" ValidationGroup="Product"
                        ControlToValidate="txtQuantity" ErrorMessage="<b>please enter Quantity</b>">
                    </asp:RequiredFieldValidator>
                </div>
            </div>
            <div style="width: 155px; float: left;">
                <div>
                    Price:
                </div>
                <div>
                    <asp:TextBox ID="txtPrice" runat="server" onblur = "GetAmount()"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvPrice" runat="server" ValidationGroup="Product"
                        ControlToValidate="txtPrice" ErrorMessage="<b>please enter Price</b>">
                    </asp:RequiredFieldValidator>
                </div>
            </div>
            <div style="width: 155px; float: left;">
                <div>
                    Amount:
                </div>
                <div>
                    <asp:TextBox ID="txtAmount" runat="server"></asp:TextBox>
                </div>
            </div>
            <div style="margin: 15px;">
                <asp:Button ID="btnAdd" runat="server" ValidationGroup="Product" Text="Add" OnClick="btnAdd_Click" />
                <asp:Button ID="btnClear" runat="server" Text="Clear" OnClick="btnClear_Click" />
            </div>
            <asp:GridView ID="GVProduct" runat="server" OnRowCancelingEdit="GVProduct_RowCancelingEdit"
                OnRowDeleting="GVProduct_RowDeleting" OnRowEditing="GVProduct_RowEditing" >
                <Columns>
                    <asp:CommandField ButtonType="Button" ShowEditButton="true" />
                    <asp:CommandField ButtonType="Button" ShowDeleteButton="true" />
                </Columns>
            </asp:GridView>
        </div>
    </div>
    <div style="padding: 5px">
        <asp:Button ID="btnSave" runat="server" ValidationGroup="Customer" Text="Save" OnClick="btnSave_Click" />
        <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
    </div>
</asp:Content>

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.Data;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection Conn = new SqlConnection();
    protected void Page_Load(object sender, EventArgs e)
    {
        CreateConnection();
    }

    public void CreateConnection()
    {
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        DataTable dt = null;
        if (ViewState["dtProduct"] != null)
            dt = (DataTable)ViewState["dtProduct"];
        else
        {
            dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Product", typeof(string)),
                            new DataColumn("Quantity", typeof(double)),
                            new DataColumn("Price",typeof(double)),
                            new DataColumn("Amount",typeof(double))});
        }

        if (btnAdd.Text == "Add")
        {
            dt.Rows.Add(txtProductName.Text, txtQuantity.Text, txtPrice.Text, txtAmount.Text);
        }
        else
        {
            int i = Convert.ToInt32(ViewState["Index"]);
            dt.Rows[i]["Product"] = txtProductName.Text;
            dt.Rows[i]["Quantity"] = txtQuantity.Text;
            dt.Rows[i]["Price"] = txtPrice.Text;
            dt.Rows[i]["Amount"] = txtAmount.Text;
        }
        GVProduct.EditIndex = -1;
        GVProduct.DataSource = dt;
        GVProduct.DataBind();
        ViewState["dtProduct"] = dt;
        ViewState["Index"] = null;
        btnAdd.Text = "Add";
        GVProduct.Enabled = true;
        ClearProduct();
    }

    public void ClearProduct()
    {
        txtProductName.Text = "";
        txtQuantity.Text = "";
        txtPrice.Text = "";
        txtAmount.Text = "";
    }

    public void Clear()
    {
        txtBillNo.Text = "";
        txtCustomerName.Text = "";
        txtAddress.Text = "";
        txtProductName.Text = "";
        txtQuantity.Text = "";
        txtPrice.Text = "";
        txtAmount.Text = "";
        ViewState["dtProduct"] = null;
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        ClearProduct();
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (ViewState["dtProduct"] != null)
        {
            CreateConnection();

            SqlCommand cmd = null;
            object obj = null;

            cmd = Conn.CreateCommand();

            cmd.CommandType = CommandType.Text;
            cmd.CommandText = "Insert into Customerdetail(BillNo,CustomerName,Address,Gender) values (" + txtBillNo.Text + "," + "'" + txtCustomerName.Text + "'" + "," + "'" + txtAddress.Text + "'" + "," + "'" + (rblGender.SelectedItem.Text == "Male" ? "Male" : "Female") + "'" + ");SELECT SCOPE_IDENTITY()";

            try
            {
                Conn.Open();
                //obj = cmd.ExecuteScalar();
                int c_id = Convert.ToInt32(cmd.ExecuteScalar());

                if (c_id > 0)
                {
                    InsertProduct(c_id);
                    lblMsg.Text = "Insert Successfull";
                }
                else
                    lblMsg.Text = "Customer insert fail";
                Clear();
                ClearProduct();
                ViewState["dtProduct"] = null;
                GVProduct.DataSource = null;
                GVProduct.DataBind();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                cmd = null;
                Conn.Close();
            }
        }
        else
        {
            lblMsg.Text = "Please Enter Product details";
        }
    }

    public void InsertProduct(int CustomerId)
    {
        DataTable dt = (DataTable)ViewState["dtProduct"];
        StringBuilder sbSql = new StringBuilder();

        sbSql.Append(@"INSERT INTO ProductDetails(CustomerId,ProductName,Quantity,Price,Amount) VALUES");
        // Response.Write("Outer Looop" + i.ToString() + "<br/><br/>");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            //  Response.Write("Inner Looop" + j.ToString() + "<br/>");
            string values = string.Format("({0},{1},{2},{3},{4}),",
                new string[] { Convert.ToString(CustomerId), "'" + dt.Rows[i]["Product"] + "'", "'" + dt.Rows[i]["Quantity"] + "'", "'" + dt.Rows[i]["Price"] + "'", "'" + dt.Rows[i]["Amount"] + "'" });
            sbSql.Append(values);
        }
        string sql = sbSql.ToString();
        sql = sql.TrimEnd(',');
        //SqlConnection con = new SqlConnection();
        //Conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = Conn;
        cmd.CommandText = sql;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.ExecuteNonQuery();
        sbSql.Clear();
    }

    protected void GVProduct_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GVProduct.DataSource = (DataTable)ViewState["dtProduct"];
        GVProduct.DataBind();
        btnAdd.Text = "Update";
        txtProductName.Text = GVProduct.Rows[e.NewEditIndex].Cells[2].Text;
        txtQuantity.Text = GVProduct.Rows[e.NewEditIndex].Cells[3].Text;
        txtPrice.Text = GVProduct.Rows[e.NewEditIndex].Cells[4].Text;
        txtAmount.Text = GVProduct.Rows[e.NewEditIndex].Cells[5].Text;
        GVProduct.Enabled = false;
        ViewState["Index"] = e.NewEditIndex;
        GVProduct.EditIndex = -1;
    }
    protected void GVProduct_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GVProduct.EditIndex = -1;
        GVProduct.DataSource = ViewState["dtProduct"];
        GVProduct.DataBind();
    }
    protected void GVProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        DataTable dt = null;
        if (ViewState["dtProduct"] != null)
            dt = (DataTable)ViewState["dtProduct"];
        dt.Rows.RemoveAt(e.RowIndex);
        ViewState["dtProduct"] = dt;
        GVProduct.DataSource = dt;
        GVProduct.DataBind();
    }
}


Wednesday, 25 December 2013

how to upload large file in chunks in MVC Api

Note : if IOs app want to use it,they need to do code to upload chunk of file.logic for that is as below:
and in c# you can use it to test by yourself by creating function in api controller with the below logic.

        [HttpPost]
        [ActionName("UploadVideo1")] (when local testing is needed)
        public string UploadVideo1(Pro_VideoMaster_Api1 video)
        {
            //Dictionary<string, dynamic> dicto;
            string FilePath=video.File;
            int Offset = 0; // starting offset.
            int ChunkSize = 65536;

            byte[] Buffer = new byte[ChunkSize];
            //opening the file for read.
            FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
            //creating the ServiceSoapClient which will allow to connect to the service.
            //WSservice.ServiceSoapClient soap_client = new WSservice.ServiceSoapClient();
            try
            {
                long FileSize = new FileInfo(FilePath).Length; // File size of file being uploaded.
                // reading the file.
                fs.Position = Offset;
                int BytesRead = 0;

                while (Offset != FileSize) // continue uploading the file chunks until offset = file size.
                {
                    BytesRead = fs.Read(Buffer, 0, ChunkSize); // read the next chunk
                    // (if it exists) into the buffer.
                    // the while loop will terminate if there is nothing left to read
                    // check if this is the last chunk and resize the buffer as needed
                    // to avoid sending a mostly empty buffer
                    // (could be 10Mb of 000000000000s in a large chunk)
                    if (BytesRead != Buffer.Length)
                    {
                        ChunkSize = BytesRead;
                        byte[] TrimmedBuffer = new byte[BytesRead];
                        Array.Copy(Buffer, TrimmedBuffer, BytesRead);
                        Buffer = TrimmedBuffer; // the trimmed buffer should become the new 'buffer'
                    }
                    // send this chunk to the server. it is sent as a byte[] parameter,
                    // but the client and server have been configured to encode byte[] using MTOM.
                    bool ChunkAppened = new VideoRepository().UploadFile(Path.GetFileName(FilePath), Buffer, Offset);
                    if (!ChunkAppened)
                    {
                        break;
                    }

                    // Offset is only updated AFTER a successful send of the bytes.
                    Offset += BytesRead; // save the offset position for resume
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                fs.Close();
            }

            return "Success";

        }


Function in Api Controller : (when consumed by IOS app)

        [HttpPost]
        [ActionName("UploadVideo")]
        public dynamic UploadVideo(Pro_VideoMaster_Api video)
        {
            Dictionary<string, dynamic> dicto;
           // byte[] b = Encoding.ASCII.GetBytes(video.buffer);
            long offset =  Convert.ToInt64(video.Offset);
            var IsSuccess = new VideoRepository().UploadFile(video.FileName, video.buffer, offset);

            dicto = new Dictionary<string, dynamic>();
            dicto.Add("Result", IsSuccess);
            dicto.Add("Message", (IsSuccess == true ? "Success" : "Failure"));

            return dicto;

        }

Function in Repository :

public bool UploadFile(string FileName, byte[] buffer, long Offset)
        {
            bool retVal = false;
            try
            {
                // setting the file location to be saved in the server.
                // reading from the web.config file
                string FilePath = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["upload_path"]);
                FilePath = Path.Combine(FilePath, FileName);

                if (Offset == 0) // new file, create an empty file
                {
                    //if(File.Exists(FilePath )){
                    File.Create(FilePath).Close();
                }
                // open a file stream and write the buffer.
                // Don't open with FileMode.Append because the transfer may wish to
                // start a different point
                using (FileStream fs = new FileStream(FilePath, FileMode.Open,FileAccess.ReadWrite, FileShare.Read))
                {
                    fs.Seek(Offset, SeekOrigin.Begin);
                    fs.Write(buffer, 0, buffer.Length);
                }
                retVal = true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            { objDBHelper = null; }

            return retVal;
        }

Wednesday, 18 December 2013

Gridview Example with helper class

web.config

 <connectionStrings>
    <add name="connectionString" connectionString="Data
     Source=WINDOWSSERVER\MSSQLSERVER2008;Database=test;UID=test;PWD=test123"
      providerName="System.Data.SqlClient" />
</connectionStrings>

 <pages>
        <controls>
          <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          <add namespace="AjaxControlToolkit" assembly="AjaxControlToolkit" tagPrefix="ajaxToolkit" />
        </controls>
</pages>

App_code -> Helper.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

/// <summary>
/// Summary description for Helpert
/// </summary>
namespace DbHelper
{
    public class Helper
    {
        SqlConnection Conn = new SqlConnection();

        public void createConnection()
        {
            Conn.ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
        }

        public DataTable ExecuteSelectCommand(string CommandName, CommandType cmdType, List<KeyValuePair<string, string>> Param)
        {
            createConnection();
            SqlCommand cmd = null;
            DataTable table = new DataTable();

            cmd = Conn.CreateCommand();

            cmd.CommandType = cmdType;
            cmd.CommandText = CommandName;
            for (int i = 0; i < Param.Count; i++)
            {
                SqlParameter param = new SqlParameter(Param[i].Key, Param[i].Value);
                cmd.Parameters.Add(param);
            }
            try
            {
                Conn.Open();

                SqlDataAdapter da = null;
                using (da = new SqlDataAdapter(cmd))
                {
                    da.Fill(table);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                cmd = null;
                Conn.Close();
            }

            return table;
        }

        public object ExecuteNonQuery(string CommandName, CommandType cmdType, List<KeyValuePair<string, string>> pars)
        {
            createConnection();
            SqlCommand cmd = null;
            object obj = null;

            cmd = Conn.CreateCommand();

            cmd.CommandType = cmdType;
            cmd.CommandText = CommandName;
            for (int i = 0; i < pars.Count; i++)
            {
                SqlParameter param = new SqlParameter(pars[i].Key, pars[i].Value);
                cmd.Parameters.Add(param);
            }

            try
            {
                Conn.Open();
                obj = cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                cmd.Dispose();
                cmd = null;
                Conn.Close();
            }

            return obj;
        }
    }
}

List Employee.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ListEmployee.aspx.cs" Inherits="_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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div>
            <asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />
        </div>
        <asp:GridView ID="GvEmployee" runat="server" AllowPaging="true" PageSize="5" AllowSorting="true"
            AutoGenerateColumns="false" Width="50%" DataKeyNames="Id"
            OnSorting="GvEmployee_Sorting"
            onpageindexchanging="GvEmployee_PageIndexChanging"
            onrowcommand="GvEmployee_RowCommand" onrowdeleting="GvEmployee_RowDeleting">
            <AlternatingRowStyle BackColor="#BFE4FF" />
            <PagerStyle BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="1px" />
            <HeaderStyle Height="30px" BackColor="#6DC2FF" Font-Size="15px" BorderColor="#CCCCCC"
                BorderStyle="Solid" BorderWidth="1px" />
            <RowStyle Height="20px" Font-Size="13px" BorderColor="#CCCCCC" BorderStyle="Solid"
                BorderWidth="1px" />
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="Designation" HeaderText="Designation" SortExpression="Designation" />
                <asp:BoundField DataField="Department" HeaderText="Department" SortExpression="Department" />
                <asp:BoundField DataField="Salary" HeaderText="Salary" SortExpression="Salary" />
                <asp:BoundField DataField="CityName" HeaderText="City Name" SortExpression="CityName" />
                <asp:TemplateField HeaderText="Edit" ItemStyle-Width="30px" HeaderStyle-Width="30px">
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkBtnEdit" runat="server" Text="Edit" Style="background-color: Transparent;"
                            CommandName="Edit" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>'/>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete" ItemStyle-Width="30px" HeaderStyle-Width="30px">
                    <ItemStyle HorizontalAlign="Center" />
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkBtnDelete" Text="Delete" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "Id") %>' runat="server" Style="background-color: Transparent;"
                            CommandName="Delete" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

ListEmployee.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 DbHelper;


public partial class _Default : System.Web.UI.Page
{
    SqlConnection Conn = new SqlConnection();
    string Sort_Direction = "Employee Name ASC";
    protected void Page_Load(object sender, EventArgs e)
    {
        Conn.ConnectionString = ConfigurationManager.ConnectionStrings["connectionString"].ToString();
        if (!IsPostBack)
        {
            ViewState["SortExpr"] = Sort_Direction;
            BindGrid();
        }
    }

    public void BindGrid()
    {
        KeyValuePair<string, string>[] array1;
        List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
        list1.Add(new KeyValuePair<string, string>("@mode", "SelectAll"));
        //list1.Add(new KeyValuePair<string, string>("two", 2));
        array1 = list1.ToArray();
        Helper objHelper = new Helper();
        DataTable dtgrid = objHelper.ExecuteSelectCommand("SP_Employee", CommandType.StoredProcedure, list1);
        GvEmployee.DataSource = dtgrid;
        GvEmployee.DataBind();
        Session["Table"] = dtgrid;
    }

    protected void GvEmployee_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataTable dtSortTable = Session["Table"] as DataTable;

        if (dtSortTable != null)
        {
            DataView dvSortedView = new DataView(dtSortTable);

            dvSortedView.Sort = e.SortExpression + " " + GetSortDirection(e.SortExpression);

            GvEmployee.DataSource = dvSortedView;
            GvEmployee.DataBind();
        }
    }
    private string GetSortDirection(string column)
    {

        // By default, set the sort direction to ascending.
        string sortDirection = "ASC";

        // Retrieve the last column that was sorted.
        string sortExpression = ViewState["SortExpression"] as string;

        if (sortExpression != null)
        {
            // Check if the same column is being sorted.
            // Otherwise, the default value can be returned.
            if (sortExpression == column)
            {
                string lastDirection = ViewState["SortDirection"] as string;
                if ((lastDirection != null) && (lastDirection == "ASC"))
                {
                    sortDirection = "DESC";
                }
            }
        }
        // Save new values in ViewState.
        ViewState["SortDirection"] = sortDirection;
        ViewState["SortExpression"] = column;

        return sortDirection;
    }

    protected void GvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GvEmployee.PageIndex = e.NewPageIndex;
        BindGrid();
    }
    protected void GvEmployee_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Equals("Edit"))
        {
            Response.Redirect("AddEmployee.aspx?type=edit&id=" + Convert.ToString(e.CommandArgument));
        }
        if (e.CommandName.Equals("Delete"))
        {
            KeyValuePair<string, string>[] array1;
            List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
            list1.Add(new KeyValuePair<string, string>("@mode", "Delete"));
            list1.Add(new KeyValuePair<string, string>("@Id", Convert.ToString(e.CommandArgument)));
            array1 = list1.ToArray();
            Helper objHelper = new Helper();
            int res = Convert.ToInt32(objHelper.ExecuteNonQuery("SP_Employee", CommandType.StoredProcedure, list1));
            BindGrid();
          
        }
    }
    protected void GvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Redirect("AddEmployee.aspx");
    }
}

Add Employee.aspx

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

<!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>
    <form id="AddEmp" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        <div>
            <div>
                Emp Name:
            </div>
            <div>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvName" ValidationGroup="Employee" runat="server"
                    Display="None" ControlToValidate="txtName" ErrorMessage="<b>Required Field Missing</b><br />Please Enter Name."
                    SetFocusOnError="True" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceName" runat="Server" TargetControlID="rfvName" />
            </div>
        </div>
        <div>
            <div>
                Birthdate:
            </div>
            <div>
                <asp:TextBox ID="txtBirthdate" runat="server"></asp:TextBox>
                <ajaxToolkit:CalendarExtender ID="ceDateGiven" TargetControlID="txtBirthdate" runat="server"
                    PopupPosition="TopLeft" />
                <asp:RequiredFieldValidator ID="rfvBirthdate" ValidationGroup="Employee" runat="server"
                    Display="None" ControlToValidate="txtBirthdate" ErrorMessage="<b>Required Field Missing</b><br />Please Enter Date."
                    SetFocusOnError="True" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceBirthdate" runat="Server" TargetControlID="rfvBirthdate" />
            </div>
        </div>
        <div>
            <div>
                Designation
            </div>
            <div>
                <asp:TextBox ID="txtDesignation" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvDesignation" ValidationGroup="Employee" runat="server"
                    Display="None" ControlToValidate="txtDesignation" ErrorMessage="<b>Required Field Missing</b><br />Please Enter Designation."
                    SetFocusOnError="True" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceDesignation" runat="Server" TargetControlID="rfvDesignation" />
            </div>
        </div>
        <div>
            <div>
                Department
            </div>
            <div>
                <asp:TextBox ID="txtDepartment" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvDepartment" ValidationGroup="Employee" runat="server"
                    Display="None" ControlToValidate="txtDepartment" ErrorMessage="<b>Required Field Missing</b><br />Please Enter Department."
                    SetFocusOnError="True" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceDepartment" runat="Server" TargetControlID="rfvDepartment" />
            </div>
        </div>
        <div>
            <div>
                Salary
            </div>
            <div>
                <asp:TextBox ID="txtSalary" runat="server"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvSalary" ValidationGroup="Employee" runat="server"
                    Display="None" ControlToValidate="txtSalary" ErrorMessage="<b>Required Field Missing</b><br />Please Enter Salary."
                    SetFocusOnError="True" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceSalary" runat="Server" TargetControlID="rfvSalary" />
            </div>
        </div>
        <div>
            <div>
                State
            </div>
            <div>
                <asp:DropDownList ID="ddlState" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlState_SelectedIndexChanged">
                </asp:DropDownList>
                <asp:RequiredFieldValidator ID="rfvState" ValidationGroup="Employee" runat="server"
                    ErrorMessage="<b>Required Field Missing</b><br />Please Select State." ControlToValidate="ddlState"
                    InitialValue="0" Display="None" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceState" runat="Server" TargetControlID="rfvState" />
            </div>
        </div>
        <div>
            <div>
                City
            </div>
            <div>
                <asp:UpdatePanel ID="upddlCity" runat="server">
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="ddlState" EventName="SelectedIndexChanged" />
                    </Triggers>
                    <ContentTemplate>
                        <asp:DropDownList ID="ddlCity" runat="server">
                            <asp:ListItem Value="0">--select City--</asp:ListItem>
                        </asp:DropDownList>
                    </ContentTemplate>
                </asp:UpdatePanel>
                <asp:RequiredFieldValidator ID="rfvCity" ValidationGroup="Employee" runat="server"
                    ErrorMessage="<b>Required Field Missing</b><br />Please Select City." ControlToValidate="ddlCity"
                    InitialValue="0" Display="None" />
                <ajaxToolkit:ValidatorCalloutExtender ID="vceCity" runat="Server" TargetControlID="rfvCity" />
            </div>
        </div>
        <div>
            <asp:Button ID="btnSave" runat="server" Text="Save" ValidationGroup="Employee" OnClick="btnSave_Click" />&nbsp;
            <asp:Button ID="btnCancel" runat="server" Text="Cancel" OnClick="btnCancel_Click" />
        </div>
    </div>
    </form>
</body>
</html>

AddEmployee.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DbHelper;
using System.Data;

public partial class AddEmployee : System.Web.UI.Page
{
    string strQSID, strQSType = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            strQSID = Request.QueryString["id"];

        if (!string.IsNullOrEmpty(Request.QueryString["type"]))
            strQSType = Request.QueryString["type"];

        if (!IsPostBack)
        {
            bindState();
            if (strQSType.Equals("edit"))
            {
                bindState();
                GetData(Convert.ToInt32(strQSID));
            }
        }
    }
    public void GetData(int Id)
    {
        if (Id > 0)
        {
            KeyValuePair<string, string>[] array1;
            List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
            list1.Add(new KeyValuePair<string, string>("@mode", "SelectById"));
            list1.Add(new KeyValuePair<string, string>("@Id",Convert.ToString(Id)));
            Helper objHepler = new Helper();
            DataTable dtEmp = objHepler.ExecuteSelectCommand("SP_Employee", CommandType.StoredProcedure, list1);
            if (dtEmp != null)
            {
                txtName.Text = dtEmp.Rows[0]["Name"].ToString();
                DateTime dt = Convert.ToDateTime(dtEmp.Rows[0]["Birthdate"]);
                txtBirthdate.Text = dt.Date.ToString("MM/dd/yyyy");
                txtDesignation.Text = dtEmp.Rows[0]["Designation"].ToString();
                txtDepartment.Text = dtEmp.Rows[0]["Department"].ToString();
                txtSalary.Text = dtEmp.Rows[0]["Salary"].ToString();
                ddlState.SelectedValue = dtEmp.Rows[0]["StateId"].ToString();
                bindCity(Convert.ToInt32(ddlState.SelectedValue));
                ddlCity.SelectedValue = dtEmp.Rows[0]["CityID"].ToString();
            }
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (strQSType.Equals("edit"))
            Savedata("Update");
        else
            Savedata("Insert");
    }

    public void Savedata(string Mode)
    {
        KeyValuePair<string, string>[] array1;
        List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
        list1.Add(new KeyValuePair<string, string>("@mode", Mode));
        if(Convert.ToInt32(strQSID) > 0)
            list1.Add(new KeyValuePair<string, string>("@Id",Convert.ToString(strQSID)));
        list1.Add(new KeyValuePair<string, string>("@Name", txtName.Text));
        list1.Add(new KeyValuePair<string, string>("@Birthdate", txtBirthdate.Text));
        list1.Add(new KeyValuePair<string, string>("@Designation", txtDesignation.Text));
        list1.Add(new KeyValuePair<string, string>("@Department", txtDepartment.Text));
        list1.Add(new KeyValuePair<string, string>("@Salary", txtSalary.Text));
        list1.Add(new KeyValuePair<string, string>("@stateId", Convert.ToString(ddlState.SelectedItem.Value)));
        list1.Add(new KeyValuePair<string, string>("@CityID", Convert.ToString(ddlCity.SelectedItem.Value)));
        Helper objHelper = new Helper();
        int res = Convert.ToInt32(objHelper.ExecuteNonQuery("SP_Employee", CommandType.StoredProcedure, list1));
        if (res > 0)
            Response.Redirect("ListEmployee.aspx");
    }

    public void bindCity(int stateId)
    {
        KeyValuePair<string, string>[] array1;
        List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
        list1.Add(new KeyValuePair<string, string>("@mode", "SelectCity"));
        list1.Add(new KeyValuePair<string, string>("@stateId", Convert.ToString(stateId)));
        array1 = list1.ToArray();
        Helper objHelper = new Helper();
        DataTable dtcity = objHelper.ExecuteSelectCommand("SP_Employee", CommandType.StoredProcedure, list1);
        if (dtcity != null)
        {
            ddlCity.DataSource = dtcity;
            ddlCity.DataTextField = "Cityname";
            ddlCity.DataValueField = "CityId";
            ddlCity.DataBind();

            ddlCity.Items.Insert(0, "--Select City--");
            ddlCity.Items[0].Value = "0";
        }
    }
    public void bindState()
    {
        KeyValuePair<string, string>[] array1;
        List<KeyValuePair<string, string>> list1 = new List<KeyValuePair<string, string>>();
        list1.Add(new KeyValuePair<string, string>("@mode", "SelectState"));
        array1 = list1.ToArray();
        Helper objHelper = new Helper();
        DataTable dtcity = objHelper.ExecuteSelectCommand("SP_Employee", CommandType.StoredProcedure, list1);
        if (dtcity != null)
        {
            ddlState.DataSource = dtcity;
            ddlState.DataTextField = "StateName";
            ddlState.DataValueField = "Stateid";
            ddlState.DataBind();

            ddlState.Items.Insert(0, "--Select state--");
            ddlState.Items[0].Value = "0";
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("ListEmployee.aspx");
    }
    protected void ddlState_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindCity(Convert.ToInt32(ddlState.SelectedValue));
    }
}


Store Procedure

USE [test]
GO
/****** Object:  StoredProcedure [dbo].[SP_Employee]    Script Date: 12/19/2013 10:51:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:        <Author,,Name>
-- Create date: <Create Date,,>
-- Description:    <Description,,>
-- =============================================
Create PROCEDURE [dbo].[SP_Employee]
    @mode varchar(20)='',
    @Id int=0,
    @Name varchar(50)='',
    @Designation varchar(50)='',
    @Department varchar(50)='',
    @Salary varchar(50)='',
    @stateId int=0,
    @CityID int=0
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
   
    If @mode = 'Insert'
    Begin
        insert into employees
        (
            Name,
            Designation,
            Department,
            Salary,
            StateId,
            CityID
        )
        Values
        (
            @Name,
            @Designation,
            @Department,
            @Salary,
            @stateId,
            @CityID
        )
        select SCOPE_IDENTITY() as returnval
    End
   
    If @mode = 'Update'
    Begin
        update employees set
            Name = @Name,
            Designation = @Designation,
            Department = @Department,
            Salary = @Salary,
            StateId=@stateId,
            CityID = @CityID
        where Id=@Id
        select @Id as returnval
    End
   
    -- SP_Employee  @mode = 'SelectAll'
    If @mode = 'SelectAll'
    Begin
        select emp.*,C.CityName from employees emp inner join Citymasters C on C.CityID = emp.CityID
    End
   
    If @mode = 'SelectById'
    Begin
        select * from employees where Id = @Id
    End
    -- SP_Employee  @mode = 'Delete',@Id=2
    If @mode = 'Delete'
    Begin
        delete from employees where Id=@Id
        select @Id as Returnval
    End
   
    If @mode = 'SelectCity'
    Begin
        select * from Citymasters where StateId = @stateId
    End
   
    If @mode = 'SelectState'
    Begin
        select * from statemaster
    End
END

Nested Grid Example

Default.aspx
 <html>
<head runat="server">
    <title>Nested Gridview in ASP.NET</title>
    <script language="javascript" type="text/javascript">
        function divexpandcollapse(divname) {
            var div = document.getElementById(divname);
            var img = document.getElementById('img' + divname);
            if (div.style.display == "none") {
                div.style.display = "inline";
                img.src = "Images/minus.gif";
            } else {
                div.style.display = "none";
                img.src = "Images/plus.gif";
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <br />
    <br />
    <table width="600px" align="center">
     <tr>
        <td colspan="2" style="background-image:url(Images/header.jpg); height:70px">
        <img src="Images/font1.png"  alt="Dotnet-Fox" height="30px"/>
        </td>
        </tr>
        <tr>
        <td colspan="2">
        <asp:GridView ID="gvEmployeeDetails" runat="server" AutoGenerateColumns="false" ShowFooter="true" Width="600px"
             OnRowDataBound="gvEmployeeDetails_OnRowDataBound">
            <Columns>
                <asp:TemplateField ItemStyle-Width="20px">
                    <ItemTemplate>
                        <a href="JavaScript:divexpandcollapse('div<%# Eval("empid") %>');">
                            <img id="imgdiv<%# Eval("empid") %>" width="9px" border="0" src="Images/plus.gif"
                                alt="" /></a>                       
                    </ItemTemplate>
                    <ItemStyle Width="20px" VerticalAlign="Middle"></ItemStyle>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Employee ID">
                <ItemTemplate>
                 <asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "empid") %>'></asp:Label>
                </ItemTemplate>
                </asp:TemplateField>               
                <asp:BoundField DataField="name" HeaderText="Name" />
                <asp:BoundField DataField="designation" HeaderText="Designation" />
                <asp:BoundField DataField="city" HeaderText="City" />
                <asp:BoundField DataField="country" HeaderText="Country" />
                <asp:TemplateField>
                    <ItemTemplate>
                    <tr>
                    <td colspan="100%">
                        <div id="div<%# Eval("empid") %>"  style="overflow:auto; display:none; position: relative; left: 15px; overflow: auto">
                        <asp:GridView ID="gv_Child" runat="server" Width="95%" AutoGenerateColumns="false" DataKeyNames="empid"
                        OnRowDataBound="gv_Child_OnRowDataBound">
                        <Columns>
                        <asp:TemplateField ItemStyle-Width="20px">
                            <ItemTemplate>
                                <a href="JavaScript:divexpandcollapse('div1<%# Eval("salary_id") %>');">
                                    <img id="imgdiv1<%# Eval("salary_id") %>" width="9px" border="0" src="Images/plus.gif"
                                        alt="" /></a>                       
                            </ItemTemplate>
                            <ItemStyle Width="20px" VerticalAlign="Middle"></ItemStyle>
                        </asp:TemplateField>
                        <asp:TemplateField HeaderText="Salary ID" Visible="false">
                            <ItemTemplate>
                             <asp:Label ID="lblSalaryID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "salary_id") %>'></asp:Label>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="salary" HeaderText="Salary"/>
                        <asp:BoundField DataField="month" HeaderText="Month"/>
                        <asp:BoundField DataField="year" HeaderText="Year"/>
                        <asp:BoundField DataField="creditedon" HeaderText="Credited On"/>
                        <asp:TemplateField>
                            <ItemTemplate>
                                <tr>
                                    <td colspan="100%">
                                        <div id="div1<%# Eval("salary_id") %>"  style="overflow:auto; display:none; position: relative; left: 15px; overflow: auto">
                                        <asp:GridView ID="gv_NestedChild" runat="server" Width="95%" AutoGenerateColumns="false">
                                        
                                            <Columns>
                                            <asp:BoundField DataField="total_working_days" HeaderText="Total working days"/>
                                            <asp:BoundField DataField="total_leave_taken" HeaderText="Total leave taken"/>
                                            </Columns>
                                            <HeaderStyle BackColor="#95B4CA" ForeColor="White" />
                                        </asp:GridView>
                                        </div>
                                    </td>
                                </tr>
                            </ItemTemplate>
                        </asp:TemplateField>
                        </Columns>
                        <HeaderStyle BackColor="#4D92C1" ForeColor="White" />
                        </asp:GridView>
                        </div>
                    </td>
                    </tr>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
            <HeaderStyle BackColor="#0063A6" ForeColor="White" />
        </asp:GridView>    
        </td>
        </tr>
        <tr>
        <td colspan="2" style="background-image:url(Images/header.jpg); height:30px"></td>
        </tr>
        </table>
    </div>
    </form>
</body>
</html>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection conn = new SqlConnection("Data Source=WINDOWSSERVER\\MSSQLSERVER2008;Database=test1;UID=epower;PWD=epower123");
    protected void Page_Load(object sender, EventArgs e)
    {      
        if (!IsPostBack)
        {           
            BindGrid();
        }
    }

    protected void BindGrid()
    {
        DataSet ds = new DataSet();       
        conn.Open();
        string cmdstr = "Select * from EmployeeDetails";
        SqlCommand cmd = new SqlCommand(cmdstr, conn);
        SqlDataAdapter adp = new SqlDataAdapter(cmd);
        adp.Fill(ds);
        cmd.ExecuteNonQuery();
        conn.Close();
        gvEmployeeDetails.DataSource = ds;
        gvEmployeeDetails.DataBind();
      
    }
    protected void gvEmployeeDetails_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblEmpID = (Label)e.Row.FindControl("lblEmpID");         
            GridView gv_Child = (GridView)e.Row.FindControl("gv_Child");

            string txtempid = lblEmpID.Text;

            DataSet ds = new DataSet();
            conn.Open();
            string cmdstr = "Select * from Salary_Details where empid=@empid";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            cmd.Parameters.AddWithValue("@empid", txtempid);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);
            cmd.ExecuteNonQuery();
            conn.Close();
            gv_Child.DataSource = ds;
            gv_Child.DataBind();
           
        }
    }

    protected void gv_Child_OnRowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Label lblSalaryID = (Label)e.Row.FindControl("lblSalaryID");
            GridView gv_NestedChild = (GridView)e.Row.FindControl("gv_NestedChild");

            string txtempid = lblSalaryID.Text;

            DataSet ds = new DataSet();
            conn.Open();
            string cmdstr = "Select * from Leave_Details where salary_id=@salary_id";
            SqlCommand cmd = new SqlCommand(cmdstr, conn);
            cmd.Parameters.AddWithValue("@salary_id", txtempid);
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            adp.Fill(ds);
            cmd.ExecuteNonQuery();
            conn.Close();
            gv_NestedChild.DataSource = ds;
            gv_NestedChild.DataBind();
        }
    }

}