export the gridview to excel sheet by clicking on submit button - c#

I am creating a c# application.
In this application I take inputs from user and using those entries I fire a sql query and dispay the results in the Gridview.
So these actions happen when we click on submit button.
After this, I want to give the user an option to export the gridview results to an excel sheet by clicking on another submit button.
the code for these things is:
aspx code:
<body>
<form id="form1" runat="server">
<div>
<b>Enter Value 1 :</b>
<asp:TextBox ID="p1" runat="server" />
<br />
<b>Enter value 2 :</b>
<asp:TextBox ID="p2" runat="server" /><br />
<asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="Start Search" />
<asp:Button ID="btn2" runat="server" OnClick="Button2_Click" Text="Export Data to Excel" />
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true"
OnPageIndexChanging="gridView_PageIndexChanging"
ShowFooter="false"
CssClass="gridstyle"
EnableViewState="false"
AllowPaging="true">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" />
<RowStyle Wrap="false" />
<HeaderStyle Wrap="false" />
</asp:GridView>
</div>
</form>
</body>
The code file for this code is:
public partial class pSearch : System.Web.UI.Page
{
SqlConnection sqlconn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString);
DataSet dsldata;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds0 = new DataSet();
ds0 = (DataSet)Session["data"];
DataView dataview_ldata = dsldata.Tables[0].DefaultView;
DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dataview_ldata;
GridView1.DataBind();
ExportToExcel(GridView1);
}
private void ExportToExcel(GridView GrdView)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GrdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string RName = Page.Request.QueryString["RName"];
string typeofquery = "mycommand";
string pv1 = p1.Text ;
string pv2 = p2.Text ;
string abc = null;
abc = "" + typeofquery + " #RName=" + RName + ",#P1='" + pv1 + "',#P2='" + pv2 + "'";
SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
GridView1.PageSize = 1000;
cmdldata.SelectCommand.CommandTimeout = 600;
dsldata = new DataSet();
ErrorHandling errhandle = new ErrorHandling();
try
{
cmdldata.Fill(dsldata);
Session["data"] = dsldata;
DataView dataview_ldata = dsldata.Tables[0].DefaultView;
DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dataview_ldata;
GridView1.DataBind();
}//end of try
catch (Exception ex)
{
String errorMessage = errhandle.displayException(ex);
Response.Write(errorMessage);
}//end of catch
finally
{
if (errhandle != null)
{
errhandle = null;
}
}//end of finally
}
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
}
I am getting an empty excel sheet right now as my output.
From my anaysis I think the following is the problem:
When button 1 is clicked Gridview is generated by the query.When button 2 is clicked , all the data that It had previously is lost (even though we can still see it on the screen).That is why I am getting an empty excel sheet right now.
Secondly,Since I am creating the gridview on button click and not on the page load,the data of the gridview is not available in the
protected void Button2_Click(object sender, EventArgs e){}
function.
Only option now to make it working is I should do the same operations of executing the query again on button2_Click function also.
But again I don't think this is an efficient way.And moreover I am running a complex query that may take 3 -4 mins at times to give the output.So running the query two times is out of question. I also tried caching the dataset but it did not work.Even creating session in not working.
I have been breaking my head on this since last 1 day. Please help me! Thank you.

Cache sounds like a good solution, could you post your cache code?
Otherwise, I would do it in ViewState. Get the result of your long query, store it in ViewState, bind the result to the GridView, then after your button click, you can access the ViewState-stored data. This isn't the best way to do it for large sets of data, because ViewState is sent across the wire with each PostBack and stored on the client side. It can really slow your application down and cause unexpected errors.
Here's my edit, that I got working locally:
Storing it in Session should work fine. Here's what I did with some dummy data. FYI, you can bind a GridView directly to a DataSet, you don't have to drill down to a DataTable or anything like that.
protected void Button1_Click(object sender, EventArgs e)
{
string RName = Page.Request.QueryString["RName"];
string typeofquery = "mycommand";
string pv1 = p1.Text;
string pv2 = p2.Text;
string abc = null;
abc = "" + typeofquery + " #RName=" + RName + ",#P1='" + pv1 + "',#P2='" + pv2 + "'";
SqlDataAdapter cmdldata = new SqlDataAdapter(abc, sqlconn);
GridView1.PageSize = 1000;
cmdldata.SelectCommand.CommandTimeout = 600;
var dummyDt = new DataTable();
dummyDt.Columns.Add("Sup");
dummyDt.Columns.Add("Bro");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dummyDt.Rows.Add("Test1", "test2");
dsldata = new DataSet();
dsldata.Tables.Add(dummyDt);
//ErrorHandling errhandle = new ErrorHandling();
try
{
//cmdldata.Fill(dsldata);
Session["data"] = dsldata;
//DataView dataview_ldata = dsldata.Tables[0].DefaultView;
//DataTable dt = dsldata.Tables[0];
GridView1.DataSource = dsldata;
GridView1.DataBind();
}//end of try
catch (Exception ex)
{
//String errorMessage = errhandle.displayException(ex);
Response.Write(ex.Message);
}//end of catch
finally
{
//if (errhandle != null)
//{
// errhandle = null;
//}
}//end of finally
}
protected void Button2_Click(object sender, EventArgs e)
{
//DataSet ds0 = new DataSet();
//ds0 = ;
//DataView dataview_ldata = dsldata.Tables[0].DefaultView;
//DataTable dt = dsldata.Tables[0];
GridView1.DataSource = (DataSet)Session["data"];
GridView1.DataBind();
ExportToExcel(GridView1);
}
private void ExportToExcel(GridView GrdView)
{
try
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.Charset = "";
// If you want the option to open the Excel file without saving than
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GrdView.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
catch (Exception ex)
{
Response.Write("<script>alert('" + ex.Message + "')</script>");
}
}

Related

How to view byte image in a gridview in asp.net?

I want to view the image in gridview from dataBase. In dataBase the image is in byte formate. How to retrieve and view that images in grid View. I don't know how to code for this.Anyone know help me to solve the issue.
To display image in gridview from database.the image is in byte
format.How to view that bytecode as image in gridview
Here is my code:
//Image Upload Code Here//
protected void Add_Click(object sender, EventArgs e)
{
if (!FileUpload1.HasFile)
{
Label2.Visible = true;
Label2.Text = "Please Select Image File"; //checking if file uploader has no file selected
}
else
{
int length = FileUpload1.PostedFile.ContentLength;
byte[] pic = new byte[length];
FileUpload1.PostedFile.InputStream.Read(pic, 0, length);
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
// SqlCommand cmd1 = new SqlCommand("insert into Student" + "(RegNo,Name,DOB,Gender,Address,Country,Picture) values(#RegNo,#Name,#DOB,#Gender,#Address,#Country,#photo)", con);
SqlCommand cmd1 = new SqlCommand("sp", con);
cmd1.CommandType = CommandType.StoredProcedure;
con.Open();
cmd1.Parameters.AddWithValue("#RegNo", RegNo.Text);
cmd1.Parameters.AddWithValue("#Name", Name.Text);
cmd1.Parameters.AddWithValue("#DOB", Dob.Text);
cmd1.Parameters.AddWithValue("#gender", Gender.SelectedValue);
cmd1.Parameters.AddWithValue("#Address", Address.Text);
cmd1.Parameters.AddWithValue("#Country", Country.Text);
//cmd1.Parameters.AddWithValue("#datetime", DateTime.Now);
cmd1.Parameters.AddWithValue("#Picture", pic);
try
{
cmd1.ExecuteNonQuery();
Label2.Visible = true;
Label2.Text = "Image Uploaded Sucessfully";
con.Close();//after Sucessfully uploaded image
}
catch(Exception ex)
{
throw ex;
}
}
Response.Redirect("~/WebForm1.aspx");
}
}
Actually there is no event with name ItemdataBound for gridview. For gridview use RowDataBound event instead. Below is the sample implementation for the same.
ASPX:
<asp:GridView runat="server" ID="grd" OnRowDataBound ="grd_RowDataBound" >
<Columns>
<asp:TemplateField HeaderText="image">
<ItemTemplate>
<img src='<%# Eval("imagedata") %>' id="imageControl" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS:
protected void grd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
System.Web.UI.HtmlControls.HtmlImage imageControl = (System.Web.UI.HtmlControls.HtmlImage)e.Row.FindControl("imageControl");
if (((DataRowView)e.Row.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64," + Convert.ToBase64String((byte[])(((DataRowView)e.Row.DataItem))["imagedata"]);
}
}
}
You can use ItemDataBound event of grid view as given below:
if(e.Item.ItemType ==ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
System.Web.UI.HtmlControls.HtmlImage imageControl =(System.Web.UI.HtmlControls.HtmlImage) e.Item.FindControl("imageControl");
if (((DataRowView)e.Item.DataItem)["imagedata"] != DBNull.Value)
{
imageControl.Src = "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
}
}
First find the image control inside your grive view and set it's image source property to "data:image/png;base64,"+ Convert.ToBase64String((byte[])((DataRowView)e.Item.DataItem)["imagedata"]) ;
Note: imagedata should be the name of column you used to save image.

How to add event on buttonfield in a datagridview

I'm currently using ASP.net and C#. I want to add an "Edit" button to my grid view, but I don't know how can I add a command on the button. And I also would gladly welcome any suggestions on how I can enhance this gridview.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["id"] == null)
{
Response.Redirect("~/LoginPage.aspx");
}
lbl_name.Text = "Welcome :: " + Session["username"];
using (MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["DBCon"].ConnectionString))
{
constructor var = new constructor();
con.Open();
string sql = "SELECT product_name,product_price,product_desc,product_stock FROM product_tbl";
MySqlCommand cmd = new MySqlCommand(sql, con);
MySqlDataReader reader1 = cmd.ExecuteReader();
reader1.Close();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "user_tbl");
GridView1.DataSource = ds.Tables["user_tbl"];
GridView1.DataBind();
}
catch (Exception ex)
{
lbl_result.Text = "ERROR>>" + ex.Message + "!";
}
finally
{
con.Close();
sql = null;
}
}
}
You can use RowCommand Event in GridView. The RowCommand Event occurs when a button is clicked in a GridView control. See this
You can add a CommandField with the Edit button:
<asp:GridView ID="GridView1" runat="server" OnRowEditing="GridView1_RowEditing" ...>
<asp:CommandField ButtonType="Link" ShowEditButton="true" ShowCancelButton="true" />
....
</asp:GridView>
And process the RowEditing event:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataSource = ...
GridView1.DataBind();
}
More details are given here: ASP.NET GridView: How to edit and delete data records.

Want to display list data in html table C#

enter image here
I want to add list data in the html Table.
The list data can be various, so table rows were dynamic and if List size increase user can use paging in table to move next...
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
Date1.Add(sdr["Date"].ToString());
Time.Add(sdr["Time"].ToString());
Event.Add(sdr["Event"].ToString());
Venue.Add(sdr["Venue"].ToString());
}
}
conn.Close();
}
}
for (int i = 0; i < Date1.Count; i++) {
string Date11 = Date1[i];
string Time1 = Time[i];
string Event1 = Event[i];
string Venue1 = Venue[i];
if(Venue1.Contains(country) || Venue1.Contains(Code[0]))
{
Result.Add( Date11 + " " + Time1 + " " + Event1 + " " + Venue1);
}
}
Can someone kindly give me code/hint which can i use in my Project. I will be very thankful to you.
The example below takes care of the following requirements which you've listed in the question:
Generates an HTML table containing your data
Has paging functionality
Supports dynamic columns
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
}
private DataTable GetEvents()
{
var table = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
using(var connection = new SqlConnection(connectionString))
{
using(var command = new SqlCommand("SELECT TOP 100 Date,Time,Event,Venue FROM Event",connection))
{
connection.Open();
var adapter = new SqlDataAdapter(command);
adapter.Fill(table);
connection.Close();
}
}
int rows = table.Rows.Count;//Place breakpoint to make sure table has rows
return table;
}
protected void gvEvents_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvEvents.PageIndex = e.NewPageIndex;
gvEvents.DataSource = this.GetEvents();
gvEvents.DataBind();
}
.ASPX:
<form id="form1" runat="server">
<asp:GridView ID="gvEvents" runat="server" AllowPaging="true" PageSize="2" OnPageIndexChanging="gvEvents_PageIndexChanging">
</asp:GridView>
</form>
Output:

asp.net panel control visibility issue

I have written a code which checks unique ID availability status.. if ID is available it should make panel visible otherwise the panel visibility is hidden. But it is not working. If i set panel visibility to false in page load it works.. but panel visibility code inside text change event of textbox, doesnt work. In my view page script manager is present to update content inside update panel. What am i doing wrong.
<asp:ScriptManager ID="scriptmanager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="PnlUsrDetails" runat="server">
<ContentTemplate>
<table>
<tr>
Enter unique no: <asp:TextBox ID="txtUniqueNo" runat="server" AutoPostBack="true" ontextchanged="txtUniqueNo_TextChanged"/>
</tr>
<tr>
<div id="checkusername" runat="server" Visible="false">
<asp:Image ID="imgstatus" runat="server" Width="17px" Height="17px"/>
<asp:Label ID="lblStatus" runat="server"></asp:Label>
</div>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Panel ID="Panel1" runat="server">
<div>Panel content</div>
</asp:Panel>
server side code:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
Panel1.Visible = false;
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Visible = false;
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Visible = true;
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
My file upload is also in update panel,, which loses its file on upload. Suggest me any alternative approaches to achieve this functionality...
Thanks
Problably cause the Control is not rendered (visible=false) and no viewstate is saved before.
Try to hide and show it with styles:
First:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
//Panel1.Visible = false; Comment
PopulateCategory();
getSubCategories(CategoryDropDownList.SelectedValue);
//CategoryDropDownList_SelectedIndexChanged(null, null);
}
}
protected void txtUniqueNo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUniqueNo.Text))
{
OdbcConnection conn = new OdbcConnection(DB.DatabaseConnString());
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Open();
OdbcCommand cmd = new OdbcCommand("select * from gallery where unique_no='" + txtUniqueNo.Text + "'", conn);
OdbcDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
Panel1.Style.Add("display", "none");
imgstatus.ImageUrl = "~/images/unavailable.png";
lblStatus.Text = "Unique Id Already Taken";
}
else
{
try
{
checkusername.Visible = true;
Panel1.Style.Add("display", "block");
imgstatus.ImageUrl = "~/images/tick.png";
lblStatus.Text = "Unique Id Available";
}
catch (Exception ex)
{
string mess = ex.Message;
}
}
}
else
{
checkusername.Visible = false;
}
}
File upload control will not work inside Update panel in this case it will lose selected file for sure.Since you have asked for alternative approach.One way is to check unique no availablity using jquery. Here is the perfect working link Check-UserName-Availability-jquery to check username availability. use this example to check unique no.
Ajax has success and error methods, so you can place your form inside a div with unique id and toggle its visibility on ajax result.
Upoo the success of ajax you can show your div in which form is present. This will eliminate the need to use script manager and update panel.

Gridview databind based on button click

I have the following in my page.
2 Asp Buttons
1 GridView
1 image button for export to excel
I need to view gridview based on respective buttons. i.e. Each button will have different data to displayed. Also gridview should allow paging as there are many records. Export to excel should also happen when image button is clicked including all pages in gridview. Can any one help in this ?
My code is following
aspx file.
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div>
<table id="Table2" width="100%" align="left" runat="server">
<tr>
<td class="auto-style8">
</td>
<td class="auto-style9"></td><td class="auto-style10">
<asp:Button ID="Admin" runat="server" Text="Admin" TOOLTIP="Sign In" TABINDEX="3" BackColor="Gray" BorderColor="Black" BorderStyle="Groove" Font-Bold="True" Font-Names="Arial" Font-Size="Large" ForeColor="White" Height="46px" Width="85px"/>
<asp:Menu ID="Menu1" runat="server" StaticSubMenuIndent="" Font-Bold="True" Font-Size="Large">
<Items>
<asp:MenuItem Text="Home" Value="Home" NavigateUrl="Admin_Main.aspx"></asp:MenuItem>
<asp:MenuItem Text="Add Customer" Value="Add Customer" NavigateUrl="Add_Details.aspx"></asp:MenuItem>
<asp:MenuItem Text="Delete Customer" Value="Delete Customer" NavigateUrl="Delete_Customer.aspx"></asp:MenuItem>
</Items>
</asp:Menu>
<asp:LinkButton ID="logout" runat="server" OnClick="logout_click" Font-Bold="True" Font-Size="Large">Logout</asp:LinkButton>
</td>
</tr>
</table>
</div>
<div>
<asp:Label ID="Label1" runat="server" Text="UserName" Font-Bold="True"
Font-Size="X-Large"></asp:Label>
<asp:TextBox ID="userName" Name= "userName" runat="server" Font-Bold="True"></asp:TextBox>
</div>
<div>
<asp:Button ID="Button2" runat="server" Text="Email Log" OnClick= "Email_Click" Height="35px" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:Button ID="Button1" runat="server" Text="All Log" Height="35px" OnClick= "Log_Click" Font-Bold="True" Font-Size="Medium" Width="90px"/>
<asp:ImageButton ID="btnexport" runat="server" Height="35px" ImageUrl="~/Images/exp-xls.gif" Width="112px" OnClick="btnExport_Click" Visible="false" />
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</asp:Content>
aspx.cs file
public partial class Display_Log : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string user = (string)(Session["user"]);
if (!IsPostBack)
{
if (user == null)
{
Response.Redirect("~/InvalidLogin.aspx");
}
else
{
Admin.Text = user;
Admin.Enabled = false;
}
}
}
protected void Email_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" Select Customer_Name,Time_Send_Clicked,Reminder_Type from Email_Log where Username='{0}'",userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment; filename=ActivityReport_" + userName.Text + ".xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
protected void Log_Click(object sender, EventArgs e)
{
SqlConnection cnn = new SqlConnection();
string connStr = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
cnn.ConnectionString = connStr;
cnn.Open();
String sqlSelect = String.Format(" SELECT [Activity],[Time],[Ticket_Number] FROM Log where Username='{0}'", userName.Text.ToString().Trim());
SqlCommand myCommand = new SqlCommand(sqlSelect, cnn);
SqlDataAdapter da = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
da.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
cnn.Close();
btnexport.Visible = true;
}
protected void logout_click(object sender, EventArgs e)
{
this.Session["user"] = null;
this.Session["group"] = null;
Response.Redirect("~/Default.aspx");
}
}
To add pagging u need to specify AllowPaging="True" this will add pagging but it wont work until u specify this which handle the onclick event when page button is clicked
onpageindexchanging="GridView1_PageIndexChanging"
<asp:GridView ID="GridView1"AutoGenerateColumns="false" DataKeyNames="Identityrowoftable" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging" />
in code behind add this
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// you need to rebind gridview here
//just set the source and databind
}
after this the print part
first you need to clear controls so unwanted elements dont come while print.
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").
GetValue(control, null);
}
catch
{ }
control.Parent.Controls.Remove(control);
}
else if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").
GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
how to use ClearControl when exporting as excel
protected void btnExport_Click(object sender, EventArgs e)
{
// Reference your own GridView here
if (GridView1.Rows.Count > 65535)
{
//DisplayError("Export to Excel is not allowed" +
// "due to excessive number of rows.");
return;
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment;filename=nameofexcelfile_" + DateTime.Now+".xls" );
Response.Charset = "";
// SetCacheability doesn't seem to make a difference (see update)
Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache);
Response.ContentType = "application/vnd.ms-excel";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
// Replace all gridview controls with literals
GridView1.PagerSettings.Visible = false;
ClearControls(GridView1);
System.Web.UI.HtmlControls.HtmlForm form
= new System.Web.UI.HtmlControls.HtmlForm();
Controls.Add(form);
form.Controls.Add(GridView1GridView1);
form.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();
}
this will print records without paging buttons

Categories