Friday, 18 May 2012

Gridview in asp.net

                            gridview in asp.net



 binding,select,update,delete,cancel,paging,sorting,add checkbox,add dropdown,add button, color on based condition,downloading file ,adding photo,show total on footer,creating pdf  using itextsharp in gridview ,creating excel and word file 

                 exporting  gridview  in excel  and word file -




      excelbutton      wordbutton

filesdwnnameid
images/Sunset.jpgdownloadmukesh9
images/Sunset.jpgdownloadraghav6
images/Winter.jpgdownloadrakesh7



coding for this


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;


public partial class Default4 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

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

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
         if (e.CommandName == "xyz")

        {

            int index = Convert.ToInt32(e.CommandArgument);

            GridViewRow row = GridView1.Rows[index];

            string fName = row.Cells[0].Text;

            Response.ContentType = "application/octet-stream";

            Response.AddHeader("Content-Disposition", "attachment;filename=" + fName);

            Response.TransmitFile(Server.MapPath("~/" + fName));

            Response.End();

        }
    }

    public void bind()
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        con.Close();
        SqlDataAdapter da = new SqlDataAdapter("select* from emp", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /*Verifies that the control is rendered */
    }


    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        SaveCheckedValues();
        GridView1.PageIndex = e.NewPageIndex;
        bind();
        PopulateCheckedValues();
    }
    private void PopulateCheckedValues()
    {
        ArrayList userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
        if (userdetails != null && userdetails.Count > 0)
        {
            foreach (GridViewRow gvrow in GridView1.Rows)
            {
                int index = (int)GridView1.DataKeys[gvrow.RowIndex].Value;
                if (userdetails.Contains(index))
                {
                    CheckBox myCheckBox = (CheckBox)gvrow.FindControl("chkSelect");
                    myCheckBox.Checked = true;
                }
            }
        }
    }
    private void SaveCheckedValues()
    {
        ArrayList userdetails = new ArrayList();
        int index = -1;
        foreach (GridViewRow gvrow in GridView1.Rows)
        {
            index = (int)GridView1.DataKeys[gvrow.RowIndex].Value;
            bool result = ((CheckBox)gvrow.FindControl("chkSelect")).Checked;
            // Check in the Session
            if (ViewState["CHECKED_ITEMS"] != null)
                userdetails = (ArrayList)ViewState["CHECKED_ITEMS"];
            if (result)
            {
                if (!userdetails.Contains(index))
                    userdetails.Add(index);
            }
            else
                userdetails.Remove(index);
        }
        if (userdetails != null && userdetails.Count > 0)
            ViewState["CHECKED_ITEMS"] = userdetails;
    }
    protected void btnExportExcel_Click(object sender, ImageClickEventArgs e)
    {
        ExportFunction("attachment;filename=GridViewExport.xls", "application/vnd.ms-excel");
    }
    protected void btnWord_Click(object sender, ImageClickEventArgs e)
    {
        ExportFunction("attachment;filename=GridViewExport.doc", "application/vnd.ms-word");
    }
    private void ExportFunction(string header, string contentType)
    {
        SaveCheckedValues();
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", header);
        Response.Charset = "";
        Response.ContentType = contentType;
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        GridView1.AllowPaging = false;
        bind();
        GridView1.HeaderRow.Style.Add("background-color", "#FFFFFF");
        GridView1.HeaderRow.Cells[0].Visible = false;
        for (int i = 0; i < GridView1.HeaderRow.Cells.Count; i++)
        {
            GridView1.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
            GridView1.HeaderRow.Cells[i].Style.Add("color", "#FFFFFF");
        }
        if (ViewState["CHECKED_ITEMS"] != null)
        {
            ArrayList CheckBoxArray = (ArrayList)ViewState["CHECKED_ITEMS"];
            int rowIdx = 0;
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                GridViewRow row = GridView1.Rows[i];
                row.Visible = false;
                int index = (int)GridView1.DataKeys[row.RowIndex].Value;
                if (CheckBoxArray.Contains(index))
                {
                    row.Visible = true;
                    row.Cells[0].Visible = false;
                }
            }
        }
        GridView1.RenderControl(hw);
        Response.Output.Write(sw.ToString());
        Response.End();
    }

}

html coding- 
note- i added  EnableEventValidation="false" in page directive for remove error validation


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

<!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>Untitled Page</title>
    <style type="text/css">
.GridviewDiv {font-size: 100%; font-family: 'Lucida Grande', 'Lucida Sans Unicode', Verdana, Arial, Helevetica, sans-serif; color: #303933;}
Table.Gridview{border:solid 1px #df5015;}
.Gridview th{color:#FFFFFF;border-right-color:#abb079;border-bottom-color:#abb079;padding:0.5em 0.5em 0.5em 0.5em;text-align:center}
.Gridview td{border-bottom-color:#f0f2da;border-right-color:#f0f2da;padding:0.5em 0.5em 0.5em 0.5em;}
.Gridview tr{color: Black; background-color: White; text-align:left}
:link,:visited { color: #DF4F13; text-decoration:none }
.highlight {text-decoration: none;color:black;background:yellow;}
</style>
</head>

<body>
    <form id="form1" runat="server">
    <div>
 
    <table>  
    <tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/images/Im-yes-and-no.jpg"
 width="40px" onclick="btnExportExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/images/yes and no.png"
 width="40px"  onclick="btnWord_Click" />
 
                                               
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
        CellPadding="2" ForeColor="Black" GridLines="None"
        onrowcommand="GridView1_RowCommand" DataKeyNames="id">
        <Columns>
        <asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
            <asp:BoundField DataField="photos" HeaderText="files" />
            <asp:TemplateField HeaderText="dwn">
            <ItemTemplate>
            <asp:LinkButton ID="lnk" runat="server" Text="download" CommandName="xyz" CommandArgument="<%#((GridViewRow)Container).RowIndex%>"></asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="name1" HeaderText="name" />
            <asp:BoundField DataField="id" HeaderText="id" />
        </Columns>
        <FooterStyle BackColor="Tan" />
        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
            HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        <HeaderStyle BackColor="Tan" Font-Bold="True" />
        <AlternatingRowStyle BackColor="PaleGoldenrod" />
    </asp:GridView>
 
     </table>
      </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>


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



<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.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>Untitled Page</title></head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"         BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px" 
        CellPadding="4" AllowPaging="True" DataKeyNames="id"
        onpageindexchanging="GridView1_PageIndexChanging" 
        onrowcancelingedit="GridView1_RowCancelingEdit" 
        onrowcommand="GridView1_RowCommand" onrowediting="GridView1_RowEditing" 
        onrowupdating="GridView1_RowUpdating" 
        onselectedindexchanged="GridView1_SelectedIndexChanged" PageSize="3" 
        onrowdatabound="GridView1_RowDataBound" ondatabound="GridView1_DataBound" 
        ShowFooter="True">
        <RowStyle BackColor="White" ForeColor="#330099" />
        <Columns>
            <asp:TemplateField HeaderText="id">
            <ItemTemplate>
            <asp:Label ID="LBL" runat="server" Text='<%# Eval("id")%>'></asp:Label>
            </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField DataField="name" HeaderText="name" />
            <asp:BoundField DataField="age" HeaderText="age" />
            <asp:BoundField DataField="sex" HeaderText="sex" />
            <asp:CommandField HeaderText="Select" ShowSelectButton="True" />
            <asp:CommandField HeaderText="edit" ShowEditButton="True" />
            <asp:CommandField HeaderText="delete" ShowDeleteButton="True" />
            <asp:TemplateField HeaderText="Check all" >
            <HeaderTemplate> <asp:CheckBox ID="ckk1" runat="server" Text="all" AutoPostBack="true" OnCheckedChanged="abc" />  </HeaderTemplate>
            <ItemTemplate> <asp:CheckBox ID="ckk1" runat="server" /></ItemTemplate>
            </asp:TemplateField>
            
            
            
            <asp:ImageField DataImageUrlField="photo" HeaderText="photo" >
            </asp:ImageField>   
            
            <asp:TemplateField HeaderText="country">
            
            <ItemTemplate>
            
            <asp:DropDownList ID="dropcountry" runat="server" DataSource='<%# country() %>' DataValueField="country" AutoPostBack="true"   ></asp:DropDownList>        
            </ItemTemplate>
            
            </asp:TemplateField>
            <asp:TemplateField HeaderText="state">
                        <ItemTemplate>
            <asp:DropDownList ID="dropstate" runat="server"  AutoPostBack="true"  ></asp:DropDownList>            
            </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="city">            
            <ItemTemplate>
            <asp:DropDownList ID="dropcity" runat="server"></asp:DropDownList>    
            </ItemTemplate>         
            
            
            </asp:TemplateField>
           
            
            <asp:TemplateField HeaderText="Button">
            
            <ItemTemplate>
            <asp:Button ID="butn1" runat="server" Text="submit"  CommandName="xyz" CommandArgument="<%#((GridViewRow)Container).RowIndex%>" />
            </ItemTemplate>
            
            </asp:TemplateField>             
            
            
                        
            <asp:TemplateField HeaderText="amount">
            <ItemTemplate>
               <asp:Label ID="LBL2" runat="server" Text= '<%# Eval( "amount","{0:c}")%>'></asp:Label>
            </ItemTemplate>
            <FooterTemplate>
             <asp:Label ID="LBLtext" runat="server" ></asp:Label>
            
            </FooterTemplate>        
            
            </asp:TemplateField>                                 
            
        </Columns>
        <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
        <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
        <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
       
    </asp:GridView>
    <p>
        &nbsp;</p>
    <div>
    
    </div>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <asp:Button ID="Button2" runat="server" onclick="Button2_Click" 
        Text="select all" />
    </form>
    <p>
        &nbsp;</p>
    </body>
</html>
cs  code :

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.IO;
using System.Drawing; 

public partial class _Default : System.Web.UI.Page 
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {  
       
    }
// this is used for editing data 
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        rebind();

    }
    public void rebind()
    {
        if (IsPostBack)
        {
            con.Open();
            SqlDataAdapter ad = new SqlDataAdapter("select *from love", con);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            GridView1.DataSource = ds;
            GridView1.DataBind();
            con.Close();
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        rebind();
    }
// this is used for cancelling editing

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        rebind();
    }
// this is used for updating data 
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        con.Open();
        TextBox name,age,sex;
        
        name = (TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0];
        age = (TextBox)GridView1.Rows[e.RowIndex].Cells[2].Controls[0];
        sex = (TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0];
       Label id = (Label)GridView1.Rows[e.RowIndex].FindControl("LBL");
       
        string sql="update love set name='"+name.Text+"',age='"+age.Text+"',sex='"+sex.Text+"' where id='"+id.Text+"'";
        SqlCommand cmd = new SqlCommand(sql, con);
        cmd.CommandType = CommandType.Text;
        int p = cmd.ExecuteNonQuery();
        if (p > 0)
        {
            Response.Write("updated successfully");
        }
        //SqlDataAdapter ad = new SqlDataAdapter(sql, con);
        //DataSet ds = new DataSet();
        //ad.Fill(ds);
        //GridView1.DataSource = ds;
        //GridView1.DataBind();
        //con.Close();
    }
// this is used to select data and get rowindex ,and on that basis get id and store in session and redirect in default2.aspx pages
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["xx"]= GridView1.SelectedRow.Cells[0].Text;
        Response.Redirect("Default2.aspx");
    }
// this is used for paging 
    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        rebind();
    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {

//  this is used to get data on basis of button click in gridview ,here  i am getting  row index and that basis finding control 
        if (e.CommandName == "xyz")
        {            
            int index = Convert.ToInt32(e.CommandArgument);
            GridViewRow row = GridView1.Rows[index];   
             string labelText = ((Label)row.FindControl("LBL")).Text.ToString();  
            Response.Redirect("Default2.aspx?name=" + labelText);
        }        
    }
// this is used to  to select all checkbox
    protected void abc(object sender, EventArgs e)
    {
        foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox chk = (CheckBox)row.FindControl("ckk1");
            if (chk.Checked==false)
            {       
      chk.Checked = true;
            }
            else
            {
                chk.Checked = false;
             }
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
         foreach (GridViewRow row in GridView1.Rows)
        {
            CheckBox b = (CheckBox)row.FindControl("ckk1");
            if (b.Checked == false)
            {
                b.Checked = true;
            }
            else
            {
                b.Checked = true;
            }
        }
    }
    decimal total;
    decimal total12;
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            total += (decimal)DataBinder.Eval(e.Row.DataItem, "amount");
        }
// this is used to show total on footer in label
        if (e.Row.RowType == DataControlRowType.Footer)
        {
            Label lb = (Label)e.Row.FindControl("LBLtext");
            lb.Text = total.ToString("c");
         }
// this is used to changes color of a particular  cell on basis of a particular condition match
        if (e.Row.RowType == DataControlRowType.DataRow)
        {     
     total12 = (decimal)DataBinder.Eval(e.Row.DataItem, "amount");
            if (total12 > 4000)      
     {
                e.Row.Cells[13].BackColor = System.Drawing.Color.Red;
            }
        }
// this is used to changes color of row on mouse over event


 if (e.Row.RowType == DataControlRowType.DataRow)
        {
            e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='Silver'");
            // This will be the back ground color of the GridView Control
            e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='White'");
        }
    }  

    public DataSet country()
    {
        con.Close();        
            con.Open();
            SqlDataAdapter ad = new SqlDataAdapter("select distinct country  from country", con);
            DataSet ds = new DataSet();
            ad.Fill(ds);
            return ds;              
    }
    public DataSet pqr()
    {      
        object str = GridView1.SelectedDataKey.Value;

        string s =Convert.ToString(str);
        
            con.Close();
            con.Open();
            SqlDataAdapter ad = new SqlDataAdapter("select distinct state  from country where country='"+s, con);
            DataSet ds = new DataSet();
            ad.Fill(ds);             
        //}
        return ds;
    }
    protected void GridView1_DataBound(object sender, EventArgs e)
    {

    }
}

   creating pdf using Itextsharp.dll 
Bottom of Form

note: download dll 4.2 if you are using vs 2008 otherwise 5.2

create a folder named bin and put it in this folder in solution explore

add two namespaces;

Using ItextSharp.text;
Using ItextSharp.text.pdf;

design look like this:


Top of Form
ame
age
sex
salary
photos
id
mukesh
23
male
2323.00
images/Sunset.jpg
9
raghav
28
male
4545.00
images/Sunset.jpg
6
rakesh
34
male
1212.00
images/Winter.jpg
7
Bottom of Form
coding -

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data.SqlClient;


public partial class _Default : System.Web.UI.Page 
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
    protected void Page_Load(object sender, EventArgs e)
    {
         if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }

        SqlDataAdapter da = new SqlDataAdapter("select* from emp", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        int columns = GridView1.Columns.Count;

        int rows = GridView1.Rows.Count;

        int tableRows = rows + 3;

        iTextSharp.text.Table gvTable = new iTextSharp.text.Table(columns, tableRows);

        gvTable.BorderWidth = 1;

        gvTable.BorderColor = new Color(0, 0, 255);

        gvTable.Cellpadding = 5;

        gvTable.Cellspacing = 5;

        Cell c1 = new Cell(" new company join us ");

        c1.Header = true;

        c1.Colspan = 2;

        gvTable.AddCell(c1);

        Cell c2 = new Cell("mukesh pdf create ");

        c2.Colspan = 2;

        gvTable.AddCell(c2);

        gvTable.AddCell("image url");

        gvTable.AddCell("id");


        for (int rowCounter = 0; rowCounter < rows; rowCounter++)

        {

            for (int columnCounter = 0; columnCounter < columns; columnCounter++)

            {

                string strValue = GridView1.Rows[rowCounter].Cells[columnCounter].Text;

                gvTable.AddCell(strValue);

            }

        }

        Document Doc = new Document();

        PdfWriter.GetInstance(Doc, Response.OutputStream);

        Doc.Open();

        Doc.Add(gvTable);

        Doc.Close();

        Response.ContentType = "application/pdf";

        Response.AddHeader("content-disposition", "attachment; filename=GridView.pdf");

        Response.End();
    }
}

html coding:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
        CellPadding="4"  >
        <RowStyle BackColor="White" ForeColor="#003399" />
        <Columns>
            <asp:BoundField DataField="name1" HeaderText="name" />
            <asp:BoundField DataField="age" HeaderText="age" />
            <asp:BoundField DataField="sex" HeaderText="sex" />
            <asp:BoundField DataField="salary" HeaderText="salary" />
            <asp:BoundField DataField="photos" HeaderText="photos" />
            <asp:BoundField DataField="id" HeaderText="id" />
        </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>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>



when click on button result looks like this:



new company join us        mukesh pdf create       ImageUrl              id
mukesh    23   male               2323.00             images/Sunset.jpg     9
raghav      28    male           4545.00             images/Sunset.jpg        6
rakesh       34    male          1212.00           images/Winter.jpg        7


      downloading files from gridview



files
dwn
name
images/Sunset.jpg
mukesh
images/Sunset.jpg
raghav
images/Winter.jpg
rakesh




codebehind  coding  for this-:


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;


public partial class Default4 : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter("select* from emp", con);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {

    }
    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
         if (e.CommandName == "xyz")

        {

            int index = Convert.ToInt32(e.CommandArgument);

            GridViewRow row = GridView1.Rows[index];

            string fName = row.Cells[0].Text;

            Response.ContentType = "application/octet-stream";

            Response.AddHeader("Content-Disposition", "attachment;filename=" + fName);

            Response.TransmitFile(Server.MapPath("~/" + fName));

            Response.End();

        }
    }
}

html design: 

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

<!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>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" 
        CellPadding="2" ForeColor="Black" GridLines="None" 
        onrowcommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField DataField="photos" HeaderText="files" />
            <asp:TemplateField HeaderText="dwn">
            <ItemTemplate>
            <asp:LinkButton ID="lnk" runat="server" Text="download" CommandName="xyz" CommandArgument="<%#((GridViewRow)Container).RowIndex%>"></asp:LinkButton>
            </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="Tan" />
        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" 
            HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
        <HeaderStyle BackColor="Tan" Font-Bold="True" />
        <AlternatingRowStyle BackColor="PaleGoldenrod" />
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    </form>
</body>
</html>


Reading Excel File in gridview first upload in folder then read in gridview-

add folder in solution explorer named images and using fileupload add  myData .xlsx file in directory

now read data and show in grid like this-


ID
Name
Status
Contact
101
mukesh
Active
10101
102
yogi
Inactive
12514821
103
gaurav
Active
154545
104
ajay
Inactive
32451548

code for this-


using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;

namespace OpenAndReadExcel
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Excel.Application appExl;
                Excel.Workbook workbook;
                Excel.Worksheet NwSheet;
                Excel.Range ShtRange;
                appExl = new Excel.ApplicationClass();
                workbook = appExl.Workbooks.Open(Server.MapPath("images/myData.xlsx"), Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                    Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                NwSheet = (Excel.Worksheet)workbook.Sheets.get_Item(1);

                int Cnum = 0;
                int Rnum = 0;

                ShtRange = NwSheet.UsedRange;
                DataTable dt = new DataTable();
                dt.Columns.Add("ID");
                dt.Columns.Add("Name");
                dt.Columns.Add("Status");
                dt.Columns.Add("Contact");
                for (Rnum = 2; Rnum <= ShtRange.Rows.Count; Rnum++)
                {
                    DataRow dr = dt.NewRow();
                    for (Cnum = 1; Cnum <= ShtRange.Columns.Count; Cnum++)
                    {
                        dr[Cnum - 1] = (ShtRange.Cells[Rnum, Cnum] as Excel.Range).Value2.ToString();
                    }
                    dt.Rows.Add(dr);
                    dt.AcceptChanges();
                }
                workbook.Close(true, Missing.Value, Missing.Value);
                appExl.Quit();


                Session["data"] = dt;
                gvOne.DataSource = dt;
                gvOne.DataBind();

            }
        }
    }


                     Apply javascript in gridview to select and deselect checkbox

by java script
salaryid
234.3412
2.3412
8.3412
4.3412


html code like this:


<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.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">
<script type="text/javascript" language="javascript">
    function SelectheaderCheckboxes(headerchk)
    {        
       
        var gvcheck = document.getElementById('GridView1');
        var i;
        if (headerchk.checked) {
            for (i = 0; i < gvcheck.rows.length; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                inputs[0].checked = true;
            }
        }
        else {
            for (i = 0; i < gvcheck.rows.length; i++) {
                var inputs = gvcheck.rows[i].getElementsByTagName('input');
                inputs[0].checked = false;
            }
        }
    }
    function Selectchildcheckboxes(header) {
      
        var count = 0;
        var gvcheck = document.getElementById('GridView1');
        var headerchk = document.getElementById(header);
        var rowcount = gvcheck.rows.length;
      
        for (i = 1; i < gvcheck.rows.length; i++) {
            var inputs = gvcheck.rows[i].getElementsByTagName('input');
            if (inputs[0].checked) {
                count++;
            }
        }
       
        if (count == rowcount - 1) {
            headerchk.checked = true;
        }
        else {
            headerchk.checked = false;
        }
    }


</script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
        <br />
        by java script</div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
        onrowdatabound="GridView1_RowDataBound" CellPadding="4"
        ForeColor="#333333" GridLines="None">
        <RowStyle BackColor="#E3EAEB" />
        <Columns>
            <asp:BoundField HeaderText="salary" DataField="salary" />
            <asp:BoundField DataField="id" HeaderText="id" />
            <asp:TemplateField HeaderText="all">
            <HeaderTemplate>
            <asp:CheckBox ID="chkheader" Text="all" runat="server" onclick="javascript:SelectheaderCheckboxes(this)"  />           
            </HeaderTemplate>
            <ItemTemplate>
            <asp:CheckBox ID="chkchild" runat="server" />
            </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <EditRowStyle BackColor="#7C6F57" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    </form>
    <p>
        &nbsp;</p>
    <p>
        by jquery</p>
</body>
</html>











cs code like this:





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
        con.Open();
        SqlCommand cmd = new SqlCommand("select salary,id from emp1", con);
        cmd.CommandType = CommandType.Text;
        DataTable dt = new DataTable();
        SqlDataReader dr = cmd.ExecuteReader();
        dt.Load(dr);
        if (dt.Rows.Count > 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }


    }


// code to deselect header checkbox if any check box is unchecked
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            CheckBox headerchk = (CheckBox)GridView1.HeaderRow.FindControl("chkheader");
            CheckBox childchk = (CheckBox)e.Row.FindControl("chkchild");
            childchk.Attributes.Add("onclick", "javascript:Selectchildcheckboxes('" + headerchk.ClientID + "')");
        }
    }
}



 



No comments:

Post a Comment