Sunday, June 16, 2013
show or hide div in jquery with example
How to Show or Hide div's using jQuery
Show DIV in jquery
jQuery('div').show(); --- Displays all the div's
jQuery('#thisdiv').show(); ---- Displays a div having the id as thisdiv
jQuery('#thisdiv div').show(); ---- Displays all the div's inside the div having the id thisdiv
Hide DIV in jquery
jQuery('div').hide(); --- Hides all the div's
jQuery('#thisdiv').hide(); ---- Hides a div having the id as thisdiv
jQuery('#thisdiv div').hide(); ---- Hides all the div's inside the div having the id thisdiv
div outside thisdiv
thisdiv
div inside thisdiv
Monday, June 3, 2013
Get or Set Http Cookies in server side of C# on Asp.Net Website
Set and Get Cookies
Get Cookie
Sample Code
HttpCookie myCookie = new HttpCookie("sampleCookie");
SampleCookie= Request.Cookies["sampleCookie"];
// Read the cookie information and display it.
if (SampleCookie!= null){
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Explanation
1.Create an object for the HttpCookie Class
HttpCookie myCookie = new HttpCookie("sampleCookie");
2. Get the Cookie from Request.Cookies Collection
SampleCookie= Request.Cookies["view"];
3.Check whether the cookie object is null
if (SampleCookie!= null)
4. Get the Cookie Value and Cookie Name
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Sample Code
Read More
Get Cookie
Sample Code
HttpCookie myCookie = new HttpCookie("sampleCookie");
SampleCookie= Request.Cookies["sampleCookie"];
// Read the cookie information and display it.
if (SampleCookie!= null){
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Explanation
1.Create an object for the HttpCookie Class
HttpCookie myCookie = new HttpCookie("sampleCookie");
2. Get the Cookie from Request.Cookies Collection
SampleCookie= Request.Cookies["view"];
3.Check whether the cookie object is null
if (SampleCookie!= null)
4. Get the Cookie Value and Cookie Name
string value= SampleCookie.Value;
string name= SampleCookie.Name;
Set Cookie
Sample Code
HttpCookie SampleCookie= new HttpCookie("SampleCookie");
SampleCookie.Value="SampleName";
SampleCookie.Name="SampleValue";
myCookie.Domain="sampleDomain.com"
SampleCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(SampleCookie);
Saturday, June 1, 2013
static vs instance members in C Sharp
Static Versus Instance Members in C#
- By default, members are per instance
- Each instance gets its own fields
- Methods apply to a specific instance
- Static members are per type
- Static methods can’t access instance data
- No this variable in static methods
Static methods
public class Area { private int side; public Rectangle(int side) { this.side= side; } public void Area() { Console.WriteLine("Area output: " + Area.CalculateArea(this.side)); } public static int CalculateArea(int side) { return side* side; } }
Sample
Friday, May 31, 2013
hasclass in jquery with example
JQuery hasClass() for single and multiple Class
The general syntax for hasClass is as follows
Check single Class
$("selector").hasClass("ClassName")
It will return true if the class is exists else return false
Check Multiple Classes
$("selector").hasClass("ClassName1 ClassName2 ClassName3")
Read More
The general syntax for hasClass is as follows
Check single Class
$("selector").hasClass("ClassName")
It will return true if the class is exists else return false
Check Multiple Classes
$("selector").hasClass("ClassName1 ClassName2 ClassName3")
<html> <head> </head> <body> <input class="found" type="button" value="Found" /> <input class="notfound" type="button" value="Not Found" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script> $(".found").click(function(){ if($(this).hasClass("found")) alert("found"); }); $(".notfound").click(function(){ if($(this).hasClass("notfound")) alert("notfound"); }); </script> </body> </html>
Thursday, April 25, 2013
How to create a data set
How to create a data set
Create your dataset and table adapter
1. Create your frame
2. Drop a Data Grid View control
3. Create a Dataset (xsd) File.
4. Open your xsd file.
5. Drag the table that you want to work with from the server explorer. Your table and table adapter will be created.
If you click the Table Adapter and check its properties you will see that the select, insert, update and delete command are automatically generated.
That depends on how your table is designed. When I was working with a table with no primary key, the updated command was not generated. You can add the command, but when it is time to update a record in the data grid view, it could generate some issues and you will not able to update.
If you do not want to deal with these problems, set a primary key field to your table when you are designing it; if you do not want to deal these problems, set a primary key field to your table when you are designing it in your data base.
Now you check the code that is created automatically in the load form event. This code will fill the data grid view with the current data in your table.
6. Enable the insert, update and delete properties in your data grid view control clicking the option control button .
7. In that same box, choose your data table as your data source
Now your data grid view columns will be generated automatically. Also as your table adapter object, binding source object and dataset object.
Also in the Load Form event this code will appear to fill with the table info every time this window form is loaded.
private void dsDemo001GUI_Load(object sender, EventArgs e)
1. Create your frame
2. Drop a Data Grid View control
3. Create a Dataset (xsd) File.
4. Open your xsd file.
5. Drag the table that you want to work with from the server explorer. Your table and table adapter will be created.
If you click the Table Adapter and check its properties you will see that the select, insert, update and delete command are automatically generated.
That depends on how your table is designed. When I was working with a table with no primary key, the updated command was not generated. You can add the command, but when it is time to update a record in the data grid view, it could generate some issues and you will not able to update.
If you do not want to deal with these problems, set a primary key field to your table when you are designing it; if you do not want to deal these problems, set a primary key field to your table when you are designing it in your data base.
Now you check the code that is created automatically in the load form event. This code will fill the data grid view with the current data in your table.
6. Enable the insert, update and delete properties in your data grid view control clicking the option control button .
7. In that same box, choose your data table as your data source
Now your data grid view columns will be generated automatically. Also as your table adapter object, binding source object and dataset object.
Also in the Load Form event this code will appear to fill with the table info every time this window form is loaded.
private void dsDemo001GUI_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'dsDemoDatabase.People' table. You can move, or remove it, as needed.
this.peopleTableAdapter.Fill(this.dsDemoDatabase.People);
}
8. Now you need to add a button that will deleted a selected record.
9. Now is time to use the event to update the records from the data grid view. Select the grid view and go to event properties section.
10. Create a CellEndEdit Event.
11. In the code go the event method and type the following code
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
}
8. Now you need to add a button that will deleted a selected record.
9. Now is time to use the event to update the records from the data grid view. Select the grid view and go to event properties section.
10. Create a CellEndEdit Event.
11. In the code go the event method and type the following code
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
this.peopleTableAdapter.Update(dsDemoDatabase);
}
Now set your grid view needs the Allow User to Add Row to TRUE.
Now create a click event button, and type the following code
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
dataGridView1.Rows.Remove(row);
this.peopleTableAdapter.Update(dsDemoDatabase); }
The button will delete the selected rows from the data grid view and then call the method Update from the Table Adapter object. Also the grid view selection mode property is change to full row selection to avoid exceptions while the row is deleting.
Depends of what you are doing the Table Adapter Object call the Update method, and update table in the Dataset and in the base. If you remove rows, calls the delete query; if you add a new row, calls the insert query; and if you are modifying an existing cell calls the update query.
Now set your grid view needs the Allow User to Add Row to TRUE.
Now create a click event button, and type the following code
private void button1_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dataGridView1.SelectedRows)
dataGridView1.Rows.Remove(row);
this.peopleTableAdapter.Update(dsDemoDatabase); }
The button will delete the selected rows from the data grid view and then call the method Update from the Table Adapter object. Also the grid view selection mode property is change to full row selection to avoid exceptions while the row is deleting.
Depends of what you are doing the Table Adapter Object call the Update method, and update table in the Dataset and in the base. If you remove rows, calls the delete query; if you add a new row, calls the insert query; and if you are modifying an existing cell calls the update query.
Tuesday, April 16, 2013
Filter Data in DataSet using C#
How to filter Data in DataSet
DataView Class is used to filter and sorting of data in Data Set
Here I m giving an example of how we can filter and sort data in data set.
DataView: A DataView is used to create different views of the data stored in a DataSet of DataTable
I am using following sqlserver database table in my example. Create a table using this script
CREATE TABLE tbemp
(
eno int NULL ,
ename varchar (50) NULL,
eadd varchar (50) NULL,
esal int NULL
)
GO
Use Following code in your .aspx page
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Data" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Filter By Salary" ToolTip="Salary > 20000 and < 50000" />
I have used following namespaces in my .cs (code) 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;
Now write followin code in your.cs file
private DataSet getdata()
{
SqlConnection con = new SqlConnection("server=tiger;database=database1;uid=sa");
SqlDataAdapter adp = new SqlDataAdapter("Select eno,ename,eadd,esal from tbemp", con);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
//Filtering Data (Showing record where salary is >20000 and <50000
DataView dv = ds.Tables[0].DefaultView;
//RowFilter is used to filter data in dataview
dv.RowFilter = "esal>=20000 and esal<=50000";// 'and' operator can be used for multipal conditions
//Sorting Record in Descending order
dv.Sort = "esal desc";//Sort property is used to data in dataview
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
GridView1.DataSource = ds;
GridView1.DataBind();
}
Read More
DataView Class is used to filter and sorting of data in Data Set
Here I m giving an example of how we can filter and sort data in data set.
DataView: A DataView is used to create different views of the data stored in a DataSet of DataTable
I am using following sqlserver database table in my example. Create a table using this script
CREATE TABLE tbemp
(
eno int NULL ,
ename varchar (50) NULL,
eadd varchar (50) NULL,
esal int NULL
)
GO
Use Following code in your .aspx page
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
<br />
<asp:Button ID="Button2" runat="server" onclick="Button2_Click"
Text="Show All Data" />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Filter By Salary" ToolTip="Salary > 20000 and < 50000" />
I have used following namespaces in my .cs (code) 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;
Now write followin code in your.cs file
private DataSet getdata()
{
SqlConnection con = new SqlConnection("server=tiger;database=database1;uid=sa");
SqlDataAdapter adp = new SqlDataAdapter("Select eno,ename,eadd,esal from tbemp", con);
DataSet ds = new DataSet();
adp.Fill(ds);
return ds;
}
protected void Button1_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
//Filtering Data (Showing record where salary is >20000 and <50000
DataView dv = ds.Tables[0].DefaultView;
//RowFilter is used to filter data in dataview
dv.RowFilter = "esal>=20000 and esal<=50000";// 'and' operator can be used for multipal conditions
//Sorting Record in Descending order
dv.Sort = "esal desc";//Sort property is used to data in dataview
GridView1.DataSource = dv;
GridView1.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
DataSet ds = getdata();
GridView1.DataSource = ds;
GridView1.DataBind();
}
Looping through DataSet in C#
To loop through DataTable, try this
Read More
if (datatable1 !=null) { foreach (DataRow dr i datatable1.Rows) { string text1 = dr["Column1Name"].ToString(); string text2 = dr["Column1Name"].ToString(); // and so on //You can also set your Literal cotrol as } }
Dataset Data set Dataset in C-sharp Dataset C-Sharp example Dataset in .net
DataSet is a collection of DataTables. We use the DataSet type to store many DataTables in a single collection. Conceptually, the DataSet acts as a set of DataTable instances. This simplifies programs that use many DataTables.
DataTable
Create
To effectively use the DataSet, you will need to have some DataTables handy. In this program, we create two DataTables. One stores two rows of patient information. And the second stores two rows of medication information.
Next:
We create a DataSet with the DataSet constructor.
Then we add the two DataTables to the DataSet instance.
Finally we print the XML.
XMLProgram that uses DataSet [C#] using System; using System.Data; class Program { static void Main() { // Create two DataTable instances. DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); table1.Rows.Add("mark", 2); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); table2.Rows.Add(2, "amoxicillin"); // Create a DataSet and put both tables in it. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Visualize DataSet. Console.WriteLine(set.GetXml()); } } Output <office> <patients> <name>sam</name> <id>1</id> </patients> <patients> <name>mark</name> <id>2</id> </patients> <medications> <id>1</id> <medication>atenolol</medication> </medications> <medications> <id>2</id> <medication>amoxicillin</medication> </medications> </office>
Dispose, using DataSet
You can put your DataSet in a using block. This ensures the Dispose method is called as soon as possible when the DataSet is no longer being used. If you are having resource usage problems, adding using blocks can help.Using
Program that creates DataSet in using block [C#] using System.Data; class Program { static void Main() { // Create a DataSet in using statement. using (DataSet set = new DataSet("office")) { // Put code that adds stuff to DataSet here. // ... The DataSet will be cleaned up outside the block. } } }
Namespace, Prefix
One important use of the DataSet is to encode data in XML format. Often, XML data needs to have an XML namespace of a tag element prefix. Fortunately, the DataSet provides the Namespace and Prefix properties to specify this.
Next:
This example specifies both the Namespace and the Prefix, and you can see them
appear in the output.
Program that uses Namespace and Prefix [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Namespace = "y"; set.Prefix = "x"; // Visualize DataSet. Console.WriteLine(set.GetXml()); } } Output <x:office xmlns:x="y"> <patients xmlns="y"> <name>sam</name> <id>1</id> </patients> </x:office>
DataSetName
Every DataSet can have a name specified. Usually, it is easiest to specify this inside the DataSet constructor. However, you can also change the name by assigning to the DataSetName property. You can also read the DataSetName property.Program that uses DataSetName [C#] using System; using System.Data; class Program { static void Main() { // Create a DataSet. DataSet set = new DataSet("office"); // Show original name. Console.WriteLine(set.DataSetName); // Change its name. set.DataSetName = "unknown"; Console.WriteLine(set.DataSetName); } } Output office unknown
Copy, Clear
The DataSet is similar to other popular collections. For example, it has a Clear method that clears all the DataTables in the set. It also provides a Copy method that will make a deep copy of all the DataTables in the set.
Tip:
If you call Copy and the Clear the original, your copied data will still exist unchanged.
Program that uses Copy and Clear [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Copy the DataSet. DataSet copy = set.Copy(); // Clear the first DataSet. set.Clear(); // Show contents. Console.WriteLine("set: {0}", set.GetXml()); Console.WriteLine("copy: {0}", copy.GetXml()); } } Output set: <office /> copy: <office> <patients> <name>sam</name> <id>1</id> </patients> <medications> <id>1</id> <medication>atenolol</medication> </medications> </office>
Tables
Understanding the Tables collection in the DataSet is important. The Tables property returns an instance of a DataTableCollection. You can use the Count property and indexer on this sub-collection to access all the individual tables.Indexer
Program that uses Tables and DataTableCollection [C#] using System; using System.Data; class Program { static void Main() { DataTable table1 = new DataTable("patients"); table1.Columns.Add("name"); table1.Columns.Add("id"); table1.Rows.Add("sam", 1); DataTable table2 = new DataTable("medications"); table2.Columns.Add("id"); table2.Columns.Add("medication"); table2.Rows.Add(1, "atenolol"); table2.Rows.Add(6, "trifluoperazine"); // Create a DataSet. DataSet set = new DataSet("office"); set.Tables.Add(table1); set.Tables.Add(table2); // Loop over DataTables in DataSet. DataTableCollection collection = set.Tables; for (int i = 0; i < collection.Count; i++) { DataTable table = collection[i]; Console.WriteLine("{0}: {1}", i, table.TableName); } // Write name of first table. Console.WriteLine("x: {0}", set.Tables[0].TableName); // Write row count of medications table. Console.WriteLine("y: {0}", set.Tables["medications"].Rows.Count); } } Output 0: patients 1: medications x: patients y: 2Also, you can get a DataTable from the Tables collection with its name. The last part of the program where we use set.Tables["medications"] shows this behavior. This is an intuitive way of getting a certain table.
Relations
The Relations property is a way to specify many DataRelations on the DataTables. A DataRelation indicates which tables are dependent on other tables (sub-tables). The Relations property is not covered in this document.CaseSensitive
The DataSet provides the CaseSensitive property. The default value of this property is False. There may be cases where you want string lookups on your DataSet to be case-sensitive.
Note:
One case involves two elements with the same name but different character casing
("Medications", "medications").
GetXml
It is possible to convert a DataSet to a string representation in XML syntax. The GetXml() method on the DataSet instance is ideal for this. The example program constructs a new DataSet instance with the name "Hospital".
Then:
It adds a new DataTable to this set.
This DataTable has four rows and five columns.
Finally:
The GetXml instance method is invoked on the DataSet,
and the result is printed to the screen.
Program that uses GetXml method [C#] using System; using System.Data; class Program { static DataTable Table() { DataTable table = new DataTable("Prescription"); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } static void Main() { // Create DataSet instance. DataSet set = new DataSet("Hospital"); // Add new table. set.Tables.Add(Table()); // Write xml data. Console.WriteLine(set.GetXml()); } } Output <Hospital> <Prescription> <Dosage>25</Dosage> <Drug>Indocin</Drug> <Patient>David</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>50</Dosage> <Drug>Enebrel</Drug> <Patient>Sam</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>10</Dosage> <Drug>Hydralazine</Drug> <Patient>Christoff</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>21</Dosage> <Drug>Combivent</Drug> <Patient>Janet</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> <Prescription> <Dosage>100</Dosage> <Drug>Dilantin</Drug> <Patient>Melanie</Patient> <Date>2010-06-17T08:39:41.0879713-06:00</Date> </Prescription> </Hospital>In the XML file, the element names Hospital, Prescription, Dosage, Drug, Patient and Date correspond to the name of the DataSet, the name of the DataTable, and then the four different DataColumns. The data is preserved.
GetXmlSchema
An XML schema is a text document that indicates the structure of an XML document. The GetXmlSchema() method on the DataSet type generates an XML schema from the known structure encoded in your DataSet.
Then:
We create a DataSet and then add a DataTable instance to it.
We call the GetXmlSchema instance method, which reveals the XML schema.
Program that demonstrates GetXmlSchema [C#] using System; using System.Data; class Program { static DataTable Table() { DataTable table = new DataTable("Prescription"); table.Columns.Add("Dosage", typeof(int)); table.Columns.Add("Drug", typeof(string)); table.Columns.Add("Patient", typeof(string)); table.Columns.Add("Date", typeof(DateTime)); table.Rows.Add(25, "Indocin", "David", DateTime.Now); table.Rows.Add(50, "Enebrel", "Sam", DateTime.Now); table.Rows.Add(10, "Hydralazine", "Christoff", DateTime.Now); table.Rows.Add(21, "Combivent", "Janet", DateTime.Now); table.Rows.Add(100, "Dilantin", "Melanie", DateTime.Now); return table; } static void Main() { // Create DataSet instance. DataSet set = new DataSet("Hospital"); // Add new table. set.Tables.Add(Table()); // Write xml schema data. Console.WriteLine(set.GetXmlSchema()); } } Output: edited <?xml version="1.0" encoding="utf-16"?> <xs:schema id="Hospital" xmlns="" xmlns:xs="" xmlns:msdata=""> <xs:element name="Hospital" msdata:IsDataSet="true" msdata:UseCurrentLocale="true"> <xs:complexType> <xs:choice minOccurs="0" maxOccurs="unbounded"> <xs:element name="Prescription"> <xs:complexType> <xs:sequence> <xs:element name="Dosage" type="xs:int" minOccurs="0" /> <xs:element name="Drug" type="xs:string" minOccurs="0" /> <xs:element name="Patient" type="xs:string" minOccurs="0" /> <xs:element name="Date" type="xs:dateTime" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema>Using XML schema with DataSet. Now that we have an XML schema file, what can we do with it? The DataSet type provides two methods, InferXmlSchema and ReadXmlSchema, which can load a file we specify that contains the schema data.
Then:
We have a DataSet with all the appropriate constraints in it.
After this, we could use ReadXml on an XML file of the data itself.
Summary
The DataSet type provides a way to collect many DataTables inside a single collection. It provides useful helper methods for acting upon those DataTables. By providing a container for DataTables, DataSet introduces a key abstraction.Convert DataSet to DataTable
A
DataSet
already contains DataTables
. You can just use:DataTable firstTable = dataSet.Tables[0];
or by name:DataTable customerTable = dataSet.Tables["Customer"];
Note that you should have using
statements for your SQL code, to ensure the connection is disposed properly:using (SqlConnection conn = ...)
{
// Code here...
}
Sunday, April 7, 2013
dataset to excel c#
here is the solution for that.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Office.Interop;
private void btn_ETexcel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 10;
for (int i = 1; i < GridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = GridView1.Columns[i - 1].HeaderText;
ExcelApp.Cells.Font.Bold = true;
}
for (int i = 0; i < GridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = GridView1.Rows.Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs ("D:\\reports.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\reports.xls");
}
Read More
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
using Microsoft.Office.Interop;
private void btn_ETexcel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 10;
for (int i = 1; i < GridView1.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = GridView1.Columns[i - 1].HeaderText;
ExcelApp.Cells.Font.Bold = true;
}
for (int i = 0; i < GridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView1.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = GridView1.Rows.Cells[j].Value.ToString();
}
}
ExcelApp.ActiveWorkbook.SaveCopyAs ("D:\\reports.xls");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Excel file created,you can find the file D:\\reports.xls");
}