Monday, June 16, 2014

Grid Edit And Update Dynamic

ASPX


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

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="drp" runat="server" AutoPostBack="true" AppendDataBoundItems="true"
            OnSelectedIndexChanged="drp_SelectedIndexChanged">
        </asp:DropDownList>
        <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Id">
                    <ItemTemplate>
                        <asp:Label ID="lblid" runat="server" Text='<%#bind("id") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="First Name">
                    <ItemTemplate>
                        <asp:Label ID="lblfirstname" runat="server" Text='<%#bind("firstname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name">
                    <ItemTemplate>
                        <asp:Label ID="ibllastname" runat="server" Text='<%#bind("lastname") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation">
                    <ItemTemplate>
                        <asp:Label ID="lbldesignation" runat="server" Text='<%#bind("designation") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Salary">
                    <ItemTemplate>
                        <asp:Label ID="lblsalary" runat="server" Text='<%#bind("salary") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile Number">
                    <ItemTemplate>
                        <asp:Label ID="iblmobilenumber" runat="server" Text='<%#bind("mobilenumber") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:TextBox ID="txtbox" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Edit">
                    <ItemTemplate>
                        <asp:LinkButton ID="linkbtn" runat="server" OnCommand="edit" Text="Edit" CommandArgument='<%#bind("id") %>'
                            CommandName='<%#bind("salary") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="btn" runat="server" Text="update" OnClick="btn_Click" />
    </div>
    </form>
</body>
</html>



-----------------------------------------------------------------------------------------------
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;

public partial class GridDynamic : System.Web.UI.Page
{
    Class1 obj;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            Session.Clear();
            obj = new Class1();
            drp.Items.Clear();
            drp.Items.Add("--Select--");
            drp.DataSource = obj.drpbind();
            drp.DataTextField = "Firstname";
            drp.DataValueField = "id";
            drp.DataBind();

        }
    }
    protected void drp_SelectedIndexChanged(object sender, EventArgs e)
    {
        obj = new Class1();
        if (Convert.ToInt32(drp.SelectedIndex) == 0)
        {
            Response.Write("select one");
        }
        else
        {
            DataSet ds = obj.grdbind(Convert.ToInt32(drp.SelectedValue));

            if (Session["dt"] == null)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add("Id", typeof(string));
                dt.Columns.Add("FirstName", typeof(string));
                dt.Columns.Add("LastName", typeof(string));
                dt.Columns.Add("Designation", typeof(string));
                dt.Columns.Add("Salary", typeof(string));
                dt.Columns.Add("MobileNumber", typeof(string));
                dt.Rows.Add(ds.Tables[0].Rows[0][0].ToString(), ds.Tables[0].Rows[0][1].ToString(), ds.Tables[0].Rows[0][2].ToString(), ds.Tables[0].Rows[0][3].ToString(), ds.Tables[0].Rows[0][4].ToString(), ds.Tables[0].Rows[0][5].ToString());
                Session["dt"] = dt;
                grd.DataSource = dt;
                grd.DataBind();

            }
            else
            {
                DataTable dt2 = (DataTable)Session["dt"];
                dt2.Rows.Add(ds.Tables[0].Rows[0][0].ToString(), ds.Tables[0].Rows[0][1].ToString(), ds.Tables[0].Rows[0][2].ToString(), ds.Tables[0].Rows[0][3].ToString(), ds.Tables[0].Rows[0][4].ToString(), ds.Tables[0].Rows[0][5].ToString());
                Session["dt"] = dt2;
                BindGrid(dt2);


            }



            foreach (GridViewRow objgrd in grd.Rows)
            {

                TextBox txt = (TextBox)objgrd.FindControl("txtbox");
                txt.Visible = false;

            }
        }
    }

    private void BindGrid(DataTable dt2)
    {
        grd.DataSource = dt2;
        grd.DataBind();
    }
    protected void edit(object sender, CommandEventArgs e)
    {

        string id = e.CommandArgument.ToString();
        string salary = e.CommandName.ToString();
        foreach (GridViewRow objgrd in grd.Rows)
        {
            TextBox txt = (TextBox)objgrd.FindControl("txtbox");
            txt.Visible = true;

        }



    }


    protected void btn_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow objgrd in grd.Rows)
        {
            obj = new Class1();
            Label lblid = (Label)objgrd.FindControl("lblid");
            Label lblsalary = (Label)objgrd.FindControl("lblsalary");
            TextBox txt = (TextBox)objgrd.FindControl("txtbox");
            //txt.Visible = true;
            if (txt.Text == "")
            {
                obj.salaryupdate(Convert.ToInt32(lblid.Text), lblsalary.Text);
            }
            else
            {
                obj.salaryupdate(Convert.ToInt32(lblid.Text), txt.Text);

            }
            DataTable dt2 = new DataTable();
            BindGrid(dt2);


        }

    }
}


------------------------------------------------------------------------------------------


Empty Rows Add in GridView

aspx Page

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

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
        <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false">
            <Columns>
                <asp:TemplateField HeaderText="Firstname">
                    <ItemTemplate>
                        <asp:TextBox ID="txtfirstname" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Lastname">
                    <ItemTemplate>
                        <asp:TextBox ID="txtlastname" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation">
                    <ItemTemplate>
                        <asp:TextBox ID="txtdesignation" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Salary">
                    <ItemTemplate>
                        <asp:TextBox ID="txtsalary" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Mobile number">
                    <ItemTemplate>
                        <asp:TextBox ID="txtmobilenumber" runat="server"></asp:TextBox>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Select">
                    <ItemTemplate>
                        <asp:ImageButton ID="imgbtn" runat="server" ImageUrl="~/Images/NARESH PIC.jpg" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:Button ID="btnRegistration" runat="server" Text="Registration" OnClick="btnRegistration_Click" />
    </div>
    </form>
</body>
</html>



---------------------------------------------------------------------------------------------------
ASPC.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;

public partial class EmptyRowsGrid : System.Web.UI.Page
{
    Class1 obj;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session.Clear();
            GridBind();

        }

    }
    protected void btnadd_Click(object sender, EventArgs e)
    {
        if (Session["dt"] == null)
        {
            GridBind();
        }
        else
        {
            DataTable dt2 = (DataTable)Session["dt"];
            dt2.Rows.Add("", "", "", "", "");
            Session["dt"] = dt2;
            grd.DataSource = dt2;
            grd.DataBind();

        }
    }

    private void GridBind()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("firstname", typeof(String));
        dt.Columns.Add("lastname", typeof(String));
        dt.Columns.Add("designation", typeof(String));
        dt.Columns.Add("salary", typeof(String));
        dt.Columns.Add("mobilenumber", typeof(String));
        dt.Rows.Add("", "", "", "", "");
        Session["dt"] = dt;
        grd.DataSource = dt;
        grd.DataBind();
    }
    protected void btnRegistration_Click(object sender, EventArgs e)
    {
        obj = new Class1();
        foreach (GridViewRow grdobj in grd.Rows)
        {
            TextBox txt1 = (TextBox)grdobj.FindControl("txtfirstname");
            TextBox txt2 = (TextBox)grdobj.FindControl("txtlastname");
            TextBox txt3 = (TextBox)grdobj.FindControl("txtdesignation");

            TextBox txt4 = (TextBox)grdobj.FindControl("txtsalary");
            TextBox txt5 = (TextBox)grdobj.FindControl("txtmobilenumber");
            if (txt5.Text == "string")
            {
                Response.Write("values please enter numbers");

            }
            else
            {
                obj.insertvalues(txt1.Text, txt2.Text, txt3.Text, txt4.Text, txt5.Text);
            }
        }
    }

}


------------------------------------------


Inner Grid

.CS CODE

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

<!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 id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="GVOuterGrid" runat="server" AutoGenerateColumns="false" OnRowDataBound="GVOuterGrid_RowDataBound" DataKeyNames="Empid">
    <Columns>
    <asp:TemplateField HeaderText="Name">
    <ItemTemplate>
    <asp:Label ID="lblDepId" runat="server" Text='<%# Bind("Empname")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    <asp:TemplateField HeaderText="Designation">
    <ItemTemplate>
    <asp:Label ID="lblDepName" runat="server" Text='<%# Bind("designation")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>



    <asp:TemplateField HeaderText="Details">
    <ItemTemplate>
    <asp:GridView ID="GVinnerGrid" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField HeaderText="Employee ID">
    <ItemTemplate>
    <asp:Label ID="lblEmpId" runat="server" Text='<%# Bind("address")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Employee Name">
    <ItemTemplate>
    <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("gender")%>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>
    </ItemTemplate>
    </asp:TemplateField>

    </Columns>
    </asp:GridView>
    </div>
    </form>
</body>

</html>


--------------------------
ASPX.CS

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

public partial class Grid : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ado OuterGridBind = new ado();
        GVOuterGrid.DataSource = OuterGridBind.outerGrid();
        GVOuterGrid.DataBind();

    }
    protected void GVOuterGrid_RowDataBound(object sender, GridViewRowEventArgs e)
    {
      

            ado InnerGridBind = new ado();
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //string depid="ssss";
                string DepId = GVOuterGrid.DataKeys[e.Row.RowIndex].Value.ToString();
                GridView inner = e.Row.FindControl("GVinnerGrid") as GridView;
                inner.DataSource = InnerGridBind.innerGrid(Convert.ToInt32(DepId));
                inner.DataBind();
            }
     
            Response.Write("Under Constraction");
      
    }
}


--------------------



Import Excel To Grid And Export Grid To Excel

aspx.cs socrce....

Add App_Code And App_Data oledb connectiuon...

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

<!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>
        Import Excel File:
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <br />
        <br />
        <asp:Button ID="btnUpload" runat="server" Text="Upload"
            onclick="btnUpload_Click" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label>
        <br />
        <asp:GridView ID="gvExcelFile" runat="server" CellPadding="2" ForeColor="Black"
            GridLines="None" BackColor="LightGoldenrodYellow" BorderColor="Tan"
            BorderWidth="1px">
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
            <FooterStyle BackColor="Tan" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <SortedAscendingCellStyle BackColor="#FAFAE7" />
            <SortedAscendingHeaderStyle BackColor="#DAC09E" />
            <SortedDescendingCellStyle BackColor="#E1DB9C" />
            <SortedDescendingHeaderStyle BackColor="#C2A47B" />
        </asp:GridView>
        <br />
        <asp:Button ID="btnExport" runat="server" Text="Export to Excel" onclick="btnExport_Click1"
 />
    </div>
    </form>
</body>

</html>

.cs file...

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.OleDb;
using System.IO;
using System.Drawing;

public partial class ExcelData : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        //Coneection String by default empty  
        string ConStr = "";
        //Extantion of the file upload control saving into ext because   
        //there are two types of extation .xls and .xlsx of Excel   
        string ext = Path.GetExtension(FileUpload1.FileName).ToLower();
        //getting the path of the file   
        string path = Server.MapPath("~/MyFolder/" + FileUpload1.FileName);
        //saving the file inside the MyFolder of the server  
        FileUpload1.SaveAs(path);
        Label1.Text = FileUpload1.FileName + "\'s Data showing into the GridView";
        //checking that extantion is .xls or .xlsx  
        if (ext.Trim() == ".xls")
        {
            //connection string for that file which extantion is .xls  
            ConStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
        }
        else if (ext.Trim() == ".xlsx")
        {
            //connection string for that file which extantion is .xlsx  
            ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
        }
        //making query  
        string query = "SELECT * FROM [Sheet1$]";
        //Providing connection  
        OleDbConnection conn = new OleDbConnection(ConStr);
        //checking that connection state is closed or not if closed the   
        //open the connection  
        if (conn.State == ConnectionState.Closed)
        {
            conn.Open();
        }
        //create command object  
        OleDbCommand cmd = new OleDbCommand(query, conn);
        // create a data adapter and get the data into dataadapter  
        OleDbDataAdapter da = new OleDbDataAdapter(cmd);
        DataSet ds = new DataSet();
        //fill the Excel data to data set  
        da.Fill(ds);
        //set data source of the grid view  
        gvExcelFile.DataSource = ds.Tables[0];
        //binding the gridview  
        gvExcelFile.DataBind();
        //close the connection  
        conn.Close();
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvExcelFile.AllowPaging = false;
        //BindGridview();
        //Change the Header Row back to white color
        gvExcelFile.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < gvExcelFile.HeaderRow.Cells.Count; i++)
        {
            gvExcelFile.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
        }
        gvExcelFile.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
    protected void btnExport_Click1(object sender, EventArgs e)
    {
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";
        using (StringWriter sw = new StringWriter())
        {
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            //To Export all pages
            gvExcelFile.AllowPaging = false;
            //this.BindGrid();

            gvExcelFile.HeaderRow.BackColor = Color.White;
            foreach (TableCell cell in gvExcelFile.HeaderRow.Cells)
            {
                cell.BackColor = gvExcelFile.HeaderStyle.BackColor;
            }
            foreach (GridViewRow row in gvExcelFile.Rows)
            {
                row.BackColor = Color.White;
                foreach (TableCell cell in row.Cells)
                {
                    if (row.RowIndex % 2 == 0)
                    {
                        cell.BackColor = gvExcelFile.AlternatingRowStyle.BackColor;
                    }
                    else
                    {
                        cell.BackColor = gvExcelFile.RowStyle.BackColor;
                    }
                    cell.CssClass = "textmode";
                }
            }

            gvExcelFile.RenderControl(hw);

            //style to format numbers to string
            string style = @"<style> .textmode { } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
}
------------------------------------------------------------------------------------------------------------