using
System;
using
System.Collections;
using
System.Collections.Generic;
using
System.Configuration;
using
System.Data;
using
System.Data.SqlClient;
using
System.IO;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
public
partial
class
_Default : System.Web.UI.Page
{
protected
void
Page_Load(
object
sender, EventArgs e)
{
if
(!IsPostBack)
{
BindGridData();
}
}
private
void
BindGridData()
{
SqlConnection con =
new
SqlConnection(ConfigurationManager.ConnectionStrings[
"con"
].ConnectionString);
SqlCommand cmd =
new
SqlCommand(
"select * from User_Details ORDER BY USER_ID ASC"
, con);
SqlDataAdapter da =
new
SqlDataAdapter(cmd);
DataSet ds =
new
DataSet();
da.Fill(ds);
ViewState[
"ds"
] = ds;
GridData.DataSource = ds;
GridData.DataBind();
}
public
override
void
VerifyRenderingInServerForm(Control control)
{
}
protected
void
GridData_PageIndexChanging(
object
sender, GridViewPageEventArgs e)
{
CheckedRecordsData();
GridData.PageIndex = e.NewPageIndex;
BindGridData();
}
private
void
ExportSelectedData(
string
header,
string
contentType)
{
CheckedRecordsData();
Response.ClearContent();
Response.AddHeader(
"content-disposition"
, header);
Response.ContentType = contentType;
StringWriter sw =
new
StringWriter();
HtmlTextWriter hw =
new
HtmlTextWriter(sw);
if
(ViewState[
"Checked_records"
] !=
null
)
{
ArrayList CheckBoxArray = (ArrayList)ViewState[
"Checked_records"
];
for
(
int
i = 0; i < GridData.Rows.Count; i++)
{
GridViewRow row = GridData.Rows[i];
row.Visible =
false
;
int
index = (
int
)GridData.DataKeys[row.RowIndex].Value;
if
(CheckBoxArray.Contains(index))
{
row.Visible =
true
;
row.Cells[0].Visible =
false
;
}
else
{
row.Visible =
false
;
row.Cells[0].Visible =
true
;
}
}
}
GridData.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.End();
}
private
void
CheckedRecordsData()
{
ArrayList userdetails =
new
ArrayList();
int
rowindex = -1;
foreach
(GridViewRow row
in
GridData.Rows)
{
if
(row.RowType == DataControlRowType.DataRow)
{
rowindex = (
int
)GridData.DataKeys[row.RowIndex].Value;
bool
result = (row.FindControl(
"chkSelect"
)
as
CheckBox).Checked;
if
(ViewState[
"Checked_records"
] !=
null
)
userdetails = (ArrayList)ViewState[
"Checked_records"
];
if
(result)
{
if
(!userdetails.Contains(rowindex))
userdetails.Add(rowindex);
}
else
userdetails.Remove(rowindex);
}
}
ViewState[
"Checked_records"
] = userdetails;
}
protected
void
btnExportToExcel_Click(
object
sender, EventArgs e)
{
ExportSelectedData(
"attachment;filename=GridViewExport.xls"
,
"application/vnd.ms-excel"
);
}
protected
void
btnExportToWord_Click(
object
sender, EventArgs e)
{
ExportSelectedData(
"attachment;filename=GridViewExport.doc"
,
"application/vnd.ms-word"
);
}
}