Wednesday, 11 December 2013
Export Grid View Data in Excel and Word in asp.net
I have one gridview that has filled with user details now I need to export gridview data to word or excel document based on selection. To implement this functionality first we need to design aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnExcel" runat="server" ImageUrl="~/ExcelImage.jpg"
onclick="btnExcel_Click" />
<asp:ImageButton ID="btnWord" runat="server" ImageUrl="~/WordImage.jpg"
onclick="btnWord_Click" />
</td>
</tr>
<tr>
<td>
<asp:GridView runat="server" ID="gvdetails" DataSourceID="dsdetails" AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="UserId" HeaderText="UserId" />
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
</td>
</tr>
</table>
<asp:SqlDataSource ID="dsdetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"/>
</div>
</form>
</body>
</html>
|
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/>
</connectionStrings>
|
After set the connection string in web.config file now we are able to get the data from database and we can bind that data to gridview by using sqldatasource. Now if you run application gridview appears like this
|
|
Now in code behind add this reference
using System.IO;
|
After that write the following code in code behind
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
/// <summary>
/// This event is used to export gridview data to word document
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnWord_Click(object sender, ImageClickEventArgs e)
{
gvdetails.AllowPaging = false;
gvdetails.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.doc"));
Response.Charset = "";
Response.ContentType = "application/ms-word";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
/// <summary>
/// This Event is used to export gridview data to Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExcel_Click(object sender, ImageClickEventArgs 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);
gvdetails.AllowPaging = false;
gvdetails.DataBind();
//Change the Header Row back to white color
gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++)
{
gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#507CD1");
}
int j = 1;
//This loop is used to apply stlye to cells based on particular row
foreach (GridViewRow gvrow in gvdetails.Rows)
{
gvrow.BackColor = Color.White;
if (j <= gvdetails.Rows.Count)
{
if (j % 2 != 0)
{
for (int k = 0; k < gvrow.Cells.Count; k++)
{
gvrow.Cells[k].Style.Add("background-color", "#EFF3FB");
}
}
}
j++;
}
gvdetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
| |
Demo for Word document
|
|
If you observe above code I added one function that isVerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we set VerifyRenderingInServerFormfunction then compiler will think that controls rendered before exporting and our functionality will work perfectly.
Here I used basic code to export gridview data to word document and for excel code is different but we can use the same code (Export to Word) for excel also to import gridview data just by replacing Customers.doc to Customers.xls and application/ms-word to application/ms-excel but here we have problem that is row background color is applied throughout excel for that reason I made some small code modification and applied color only to the particular columns based on rows.
Demo for Excel document
How to Hide and Show DVD drive in window 7
How to hide a partition in Windows?
-Right-Click on My Computer [Computer in Windows Vista and Windows 7]
-Click on Manage.
-From the list of options Click on Disk Management that will be located in the left-bottom section.
-All your hard disk and its partitions will be show in the right hand side.
-Right-Click on the partition that you want to hide and select .
-"Change Drive Letters and Path"
-Click on "Remove" and click "Yes"
-Your drive will now be hidden in my computer.
To unhide the drive :
-Go to Disk Management Right-Click on the hidden partition [there will not be a drive letter on the hidden drive] again select
-"Change Drive Letters and Path"
-Click on add and select an appropriate drive letter.
-Click Ok
-Now the drive is unhided.
Tuesday, 10 December 2013
Enable and Disable button in gridview in asp.net
In this article a GridView that has a number of buttons that you need to enable or disable all at once and don't want to have to force a post back on your users in order to loop through them all. By using only a simple js function.
When a GridView renders on the page, it is simply an HTML table and you can traverse it just like you would any other HTML table using JavaScript.
The following code to do a basic version of this in order to enable or disable all buttons in a GridView. First the code gets an instance of the GridView using the ClientID of the GridView, then create a collection of all input controls in the GridView. Next it loops through each input control and checks the type (this is necessary because input controls include not only submit buttons but also things like textboxes). Finally we either enable or disable the submit button.
<script type="text/javascript" language="javascript"> function disableButtons() { var gridViewID = "<%=gvReporter.ClientID %>"; var gridView = document.getElementById(gridViewID); var gridViewControls = gridView.getElementsByTagName("input"); for (i = 0; i < gridViewControls.length; i++) { // if this input type is button, disable if (gridViewControls[i].type == "submit") { gridViewControls[i].disabled = true; } } } function enableButtons() { var gridViewID = "<%=gvReporter.ClientID %>"; var gridView = document.getElementById(gridViewID); var gridViewControls = gridView.getElementsByTagName("input"); for (i = 0; i < gridViewControls.length; i++) { // if this input type is button, disable if (gridViewControls[i].type == "submit") { gridViewControls[i].disabled = false; } } } </script>
How to remove special characters from textbox using javascript
Sometime you might come into a situation to remove the specials characters in the textbox while users give the input. Below JavaScript sample code will help you to remove those char from textbox. The following script delete all the special character on textbox "onkeyup" event.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Remove Special Characters from the Textbox - Coding cluster</title>
<script language="javascript" type="text/javascript">
function deleteSpecialChar(txtName) {
if (txtName.value != '' && txtName.value.match(/^[\w ]+$/) == null)
{
txtName.value = txtName.value.replace(/[\W]/g, '');
}
}
</script>
</head>
<body>
<form id="form1" >
<div>
<input id="txtName" type="text" onkeyup="javascript:deleteSpecialChar(this)" />
</div>
</form>
</body>
</html>
Displaying Festival names on calendar control in asp.net
This is an article for showing festival names on a specific date on calendar control. First create a SQL table with following fields HolidayName, HolidayDate. And fulfill the festival name in "HolidayName" field and festival date in "HolidayDate" field.
Then took one Calendar control on to the page(Calendar.aspx)
Copy and paste the following code into your Calendar.aspx file
<form id="form1" runat="server">
<div>
<asp:calendar ondayrender="Calendar1_DayRender" id="Calendar1" runat="server" backcolor="#FFFFCC" bordercolor="#FFCC66" borderwidth="1px" daynameformat="Shortest" names="Verdana" size="8pt" forecolor="#663399" height="200px" showgridlines="True" width="300px">
<selecteddaystyle backcolor="#CCCCFF" bold="True">
<selectorstyle backcolor="#FFCC66">
<todaydaystyle backcolor="#FFCC66" forecolor="White">
<othermonthdaystyle forecolor="#CC9966">
<nextprevstyle size="9pt" forecolor="#FFFFCC">
<dayheaderstyle backcolor="#FFCC66" bold="True" height="1px">
<titlestyle backcolor="#990000" bold="True" size="9pt" forecolor="#FFFFCC">
</titlestyle>
</dayheaderstyle></nextprevstyle></othermonthdaystyle></todaydaystyle></selectorstyle></selecteddaystyle></asp:calendar></div>
</form>
<span style="font-weight: bold; color: rgb(51, 51, 255);font-size:130%;"></span>
Then Copy and paste the following code into your Calendar.aspx.cs file
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;
public partial class _Default : System.Web.UI.Page
{
SqlConnection con;
protected void Page_Load(object sender, EventArgs e)
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["YourConnectionString"].ConnectionString);
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
CalendarDay day = (CalendarDay)e.Day;
SqlCommand cmd = new SqlCommand("select HolidayName,HolidayDate from Holidays", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (day.Date.ToString() == dr["HolidayDate"].ToString())
{
TableCell cell = (TableCell)e.Cell;
string s1 = dr["HolidayName"].ToString();
if (s1 != null)
{
cell.BackColor = System.Drawing.Color.LightGray;
cell.Controls.Add(new LiteralControl("
" + s1));
}
}
}
con.Close();
}
}
How to create editable calender in asp.net with database
ASPX PAGE
...........................................................................................
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:Calendar ID="Calendar1" runat="server" BackColor="White"
BorderColor="Black" DayNameFormat="Shortest" Font-Names="Times New Roman"
Font-Size="10pt" ForeColor="Black" Height="343px" NextPrevFormat="FullMonth"
ondayrender="Calendar1_DayRender"
onselectionchanged="Calendar1_SelectionChanged"
onvisiblemonthchanged="Calendar1_VisibleMonthChanged" TitleFormat="Month"
Width="888px">
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt"
ForeColor="#333333" Height="10pt" />
<DayStyle Width="14%" />
<NextPrevStyle Font-Size="8pt" ForeColor="White" />
<OtherMonthDayStyle ForeColor="#999999" />
<SelectedDayStyle BackColor="#CC3333" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" Font-Bold="True" Font-Names="Verdana"
Font-Size="8pt" ForeColor="#333333" Width="1%" />
<TitleStyle BackColor="Black" Font-Bold="True" Font-Size="13pt"
ForeColor="White" Height="14pt" />
<TodayDayStyle BackColor="#CCCC99" />
</asp:Calendar>
</asp:Content>
CS PAGE
..........................................................................................................
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;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected DataSet dsHolidays;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Calendar1.VisibleDate = DateTime.Today;
FillHolidayDataset();
}
}
protected void FillHolidayDataset()
{
DateTime firstDate = new DateTime(Calendar1.VisibleDate.Year,
Calendar1.VisibleDate.Month, 1);
DateTime lastDate = GetFirstDayOfNextMonth();
dsHolidays = GetCurrentMonthData(firstDate, lastDate);
}
protected DateTime GetFirstDayOfNextMonth()
{
int monthNumber, yearNumber;
if (Calendar1.VisibleDate.Month == 12)
{
monthNumber = 1;
yearNumber = Calendar1.VisibleDate.Year + 1;
}
else
{
monthNumber = Calendar1.VisibleDate.Month + 1;
yearNumber = Calendar1.VisibleDate.Year;
}
DateTime lastDate = new DateTime(yearNumber, monthNumber, 1);
return lastDate;
}
protected DataSet GetCurrentMonthData(DateTime firstDate,
DateTime lastDate)
{
DataSet dsMonth = new DataSet();
ConnectionStringSettings cs;
cs = ConfigurationManager.ConnectionStrings["ConnectionString1"];
String connString = cs.ConnectionString;
SqlConnection dbConnection = new SqlConnection(connString);
String query;
query = "SELECT HolidayDate,Text FROM Holidays " + " WHERE HolidayDate >= @firstDate AND HolidayDate < @lastDate";
SqlCommand dbCommand = new SqlCommand(query, dbConnection);
dbCommand.Parameters.Add(new SqlParameter("@firstDate",
firstDate));
dbCommand.Parameters.Add(new SqlParameter("@lastDate", lastDate));
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(dbCommand);
try
{
sqlDataAdapter.Fill(dsMonth);
}
catch {}
return dsMonth;
}
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
}
protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)
{
DateTime nextDate;
if (dsHolidays != null)
{
foreach (DataRow dr in dsHolidays.Tables[0].Rows)
{
nextDate = (DateTime)dr["HolidayDate"];
if (nextDate == e.Day.Date)
{
e.Cell.BackColor = System.Drawing.Color.Yellow;
e.Cell.Text = nextDate.Day + "<br/> " + dr["Text"].ToString();
}
}
}
}
protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
FillHolidayDataset();
}
}
}
........................................................................................
CREATE TABLE [dbo].[Holidays](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[HolidayDate] [datetime] NULL,
[Text] [nvarchar](max) NULL
)
How to create Page Hit counter in asp.net
Create XML page
.........................................................................................................................................
<?xml version="1.0" encoding="utf-8" ?>
<counter>
<count>
<hits>0</hits>
</count>
</counter>
Create UserControl.aspx
.......................................................................................................................................................
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="counter.ascx.cs" Inherits="counter"%>
<asp:Label ID="lblCounter" runat="server"></asp:Label>
code usercontrol.cs page
............................................................................................................................................
protected void Page_Load(object sender, EventArgs e)
{
this.countMe();
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
lblCounter.Text = tmpDs.Tables[0].Rows[0]["hits"].ToString();
}
private void countMe()
{
DataSet tmpDs = new DataSet();
tmpDs.ReadXml(Server.MapPath("~/counter.xml"));
int hits = Int32.Parse(tmpDs.Tables[0].Rows[0]["hits"].ToString());
hits += 1;
tmpDs.Tables[0].Rows[0]["hits"] = hits.ToString();
tmpDs.WriteXml(Server.MapPath("~/counter.xml"));
}
Subscribe to:
Posts (Atom)




