Export Gridview to Excel In ASP.Net

There often is a need in a project's reporting module to show records of a GridView in an Excel sheet, so to do that I decided to write this article, especially focusing on beginners and those who want to learn how to export a GridView to Excel Using ASP.Net C#.
Now before creating the application, let us create a table named employee in a database with records for the GridView, the table has the following fields (shown in the following image):
 
I hope you have created the same type of table.
Now create the project as:
  1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
  2. "File" - "New Project" - "C#" - "Empty Project" (to avoid adding a master page).
  3. Provide the Project name such as "ExportGridToExcel" or another as you wish and specify the location.
  4. Then right-click on the Solution Explorer and select "Add New Item" - "Default.aspx" page.
  5. Then add one button, one label and a GridView to the page.
Now let us create a function to bind the records to the GridView from the database.Now create the following function in the default.aspx.cs page to bind the GridView:
private void Bindgrid()  
   {  
       connection();  
//not recommended this i have written for example,write stored procedure for security  
       query = "select *from Employee";
       com = new SqlCommand(query, con);  
       SqlDataReader dr = com.ExecuteReader();  
       GridView1.DataSource = dr;  
       GridView1.DataBind();  
       con.Close();     
                  
   }  
Now, call this function on page load as in the following:
protected void Page_Load(object sender, EventArgs e)  
  {  
      if (!IsPostBack)  
      {  
          Bindgrid();  
        
      }  
  } 
Now run the application, we then can see the following records in the GridView as in the following:

Now, we have a record to export to Excel, let us start coding for our actual requirements. Add the VerifyRenderingInServerForm event after the page load that is required while exporting the GridView to Excel,Word and PDF formt to avoid the runtime error that occurrs, such as "GridView' must be placed inside a form tag with runat=server.".
public override void VerifyRenderingInServerForm(Control control)  
   {  
       //required to avoid the run time error "  
       //Control 'GridView1' of type 'Grid View' must be placed inside a form tag with runat=server."  
   } 
Now create the following function to Export the GridView to Excel as in the following:
private void ExportGridToExcel()  
   {  
       Response.Clear();  
       Response.Buffer = true;  
       Response.ClearContent();  
       Response.ClearHeaders();  
       Response.Charset = "";  
       string FileName ="Vithal"+DateTime.Now+".xls";  
       StringWriter strwritter = new StringWriter();  
       HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);        
       Response.Cache.SetCacheability(HttpCacheability.NoCache);  
       Response.ContentType ="application/vnd.ms-excel";    
       Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);  
       GridView1.GridLines = GridLines.Both;  
       GridView1.HeaderStyle.Font.Bold = true;  
       GridView1.RenderControl(htmltextwrtter);  
       Response.Write(strwritter.ToString());  
       Response.End();      
  
   }  
Now double-click on the "Export to Excel" button and call the preceding function in "onclick" as in the following:
protected void Button1_Click(object sender, EventArgs e)  
  {  
      ExportGridToExcel();  
  }  
Now the entire code of the Default.aspx.cs page will be as follows:
using System;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.Configuration;  
using System.Data.SqlClient;  
using System.IO;  
using System.Web;  
  
public partial class _Default : System.Web.UI.Page  
{  
    private SqlConnection con;  
    private SqlCommand com;  
    private string constr,query;  
    private void connection()  
    {  
        constr = ConfigurationManager.ConnectionStrings["getconn"].ToString();  
        con = new SqlConnection(constr);  
        con.Open();  
      
    }  
    protected void Page_Load(object sender, EventArgs e)  
    {  
        if (!IsPostBack)  
        {  
            Bindgrid();  
          
        }  
    }  
  
    public override void VerifyRenderingInServerForm(Control control)  
    {  
        //required to avoid the runtime error "  
        //Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server."  
    }  
  
    private void Bindgrid()  
    {  
        connection();  
        query = "select *from Employee";//not recommended this i have wrtten just for example,write stored procedure for security  
        com = new SqlCommand(query, con);  
        SqlDataReader dr = com.ExecuteReader();  
        GridView1.DataSource = dr;  
        GridView1.DataBind();  
        con.Close();     
                   
    }  
    protected void Button1_Click(object sender, EventArgs e)  
    {  
        ExportGridToExcel();  
    }  
    private void ExportGridToExcel()  
    {  
        Response.Clear();  
        Response.Buffer = true;  
        Response.ClearContent();  
        Response.ClearHeaders();  
        Response.Charset = "";  
        string FileName ="Vithal"+DateTime.Now+".xls";  
        StringWriter strwritter = new StringWriter();  
        HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);        
        Response.Cache.SetCacheability(HttpCacheability.NoCache);  
        Response.ContentType ="application/vnd.ms-excel";    
        Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);  
        GridView1.GridLines = GridLines.Both;  
        GridView1.HeaderStyle.Font.Bold = true;  
        GridView1.RenderControl(htmltextwrtter);  
        Response.Write(strwritter.ToString());  
        Response.End();      
  
    }  
  
}  
Now run the application and click on the "Export to Excel" button, the following popup is shown:

Now click on the "Open with" option, all the GridView records are exported into Excel as in the following:

Notes
  • Change the connection string in the web.config file to specify your server location.
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me, including beginners.

Difference Between Method Overloading and overriding C#

In this article we will learn what is the difference between  Method Overloading and overriding in C# with the help of example .
 I have written this article focusing on students and beginners. So before proceeding further please refer to my previous articles for a better understanding.
So let us start from Method Overloading

What is  Method Overloading ?
Creating a multiple methods in a class with same name but different parameters and types is called as method overloading.method overloading is the example of Compile time polymorphism which is  done at compile time.
 Method overloading can be achieved by using following things :
  • By changing the number of parameters used.
  • By changing the order of parameters.
  • By using different data types for the parameters.
e.g
public class Methodoveloading    
  {    
//two int type Parameters method 
    public int add(int a, int b)   
    {    
        return a + b;    
        
    }  
//three int type Parameters with same method same as above    
    public int add(int a, int b,int c)  
    {    
        return a + b+c;    
    
    } 
  //four float type Parameters with same method same as above two method    
    public float add(float a, float b,float c,float d) 
    {    
        return a + b+c+d;    
    
    }    
  }  
 In the above example ,their are three methods with same method same but they differ with number of parameters and type of parameters ,hence this types of methods is called as method overloading.
FAQ of Method Overloading
Q. Can method overloading has same numbers of parameters and Name with different return types?
Ans. No, because conflict is happen in methods while passing the parameters .
Now let us learn about the Method overriding
What is Method overriding ?
Creating the method in a derived class with same name, same parameters and same return type as in base class is called as method overriding.
Method overriding is the example of run time polymorphism,how its is the part of run time polymorphism i will explain in detail.
Some Key Points of  Method overriding
  •  Method overriding is only possible in derived class not within the same class where the method is declared.
  • Only those methods are overrides in the derived class which is declared in the base class with the help of virtual keyword or abstract keyword.
 e.g
public class Account
  {  
    public virtual int balance()  
    {  
        return 10;  
    }  
  }  
public class Amount:Account
{  
     
    public override int balance()  
    {  
        return 500;  
    }  
}  

Output of the above Program is
  • 10 and 500
In the above small program their are two classes Account and Amount and both the classes contain same method Name that balance() in which Account class method  returns 10 and  Amount class returns 500 at run time because Account class  method is overridden in a class Amount.
The Method overriding is very useful when  we wants to return different output of same method in different class according to the need.
Let us consider the example I wants to provide the discount on particular product according to the Customer category that A,B,C in this scenario suppose A,B,C are the classes and Discount is the class which contains virtual CustDiscount () method ,then i simply override it on class A,B,C instead of writing three different methods for each class.
I hope you understand about the  Method overriding and Method overloading,In my next article we will see the real time examples of Method overriding and Method overloading.
Summary
I hope this article is useful for all students and beginners. If you have any suggestion related to this article then please contact me.

Difference Between Abstract Class and Interfaces In C#

Abstract Class and Interfaces are always hot topics in C# language in terms of many ways including interviews and normal developer discussions during lunch and walk .So to add something in it and to help beginners and students  I have decided to write this small article to explain difference between Abstract Class and Interfaces.
So lets see
Abstract Class Interfaces
Classes may inherit only one abstract class. Class may inherit multiple interfaces.
Abstract Class members have access modifiers. Interface members are by default public.
Abstract Class methods have implementation or no implementation. Interface methods have no implementation.
An Abstract Class contains abstract as well as non-abstract methods. Interface has only abstract methods.
When you want an implementation or no implementation of methods then use an abstract class. If you do not want any implementation of methods then use interfaces.
For more details about Abstract and Interfaces please refer my following articles
Summary 
I hope this article is useful for all readers , If you have any suggestion regarding this article then please contact me. 

Difference Between Class and Interfaces In C#

In this article we will learn about the difference between the class and Interfaces , I got many emails and request from students and beginners to write something about it , So I have decided to write this article .
Instead of going depth lets start differentiation between these two as interview question prospective .

Class Interfaces
Classes have any access modifier. It cannot be allowed to be declared as private.
We can create instances of classes. Cannot create an instance of an interface.
Class members have any access modifiers. Cannot apply any access modifier to members because by default they are public.
Class methods have an implementation. Interface methods have no implementation.
A class contains any type of method. Interface has only abstract methods.
Cannot inherit multiple classes. Multiple Interfaces are inherited.

For more depth details about classes and Interfaces please refer my following articles
Summary 
I hope this article is useful for all readers , If you have any suggestion regarding this article then please contact me or you can post your suggestion in comment box.  

How To Get Session Value in Static Method

We can not be use the Session object in static method so to its problem while reading the session value in static method ,to overcome this problem we need to read session value like as shown in following code snippet: 



HttpContext.Current.Session["UserName"].ToString();  

Summary 
I hope this code snippet is useful ,if you have any suggestion regarding this article then please contact me.

Overview of Object Oriented Programming in C#

In this article we will learn overview of object oriented programming language . I have written this article  completely  focusing on beginners to make them understand about the OOPS concept.

Introduction

The programming in which data is logically represented in the form of a class and physically represented in the form an object is called as object oriented programming (OOP). OOP has the following important features.
    Class
      In OOP languages it is must to create a class for representing data. Class contains variables for storing data and functions to specify various operations that can be performed on data. Class will not occupy any memory space and hence it is only logical representation of data.
      Refer following article for depth explanation 
        Encapsulation
          Within a class variables are used for storing data and functions to specify various operations that can be performed on data. This process of wrapping up of data and functions that operate on data as a single unit is called as data encapsulation.
          Refer following article for depth explanation
            Abstraction
              Within a class if a member is declared as private, then that member can not be accessed from out side the class. I.e. that member is hidden from rest of the program. This process of hiding the details of a class from rest of the program is called as data abstraction. Advantage of data abstraction is security.

              Refer following article for depth explanation 
                Object and Instance
                  Class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, which is called as an object. When an object is created by using the keyword new, then memory will be allocated for the class in heap memory area, which is called as an instance and its starting address will be stored in the object in stack memory area.
                  When an object is created without the keyword new, then memory will not be allocated in heap I.e. instance will not be created and object in the stack contains the value null. When an object contains null, then it is not possible to access the members of the class using that object.
                    Inheritance
                      Creating a new class from an existing class is called as inheritance. When a new class requires same members as an existing class, then instead of recreating those members the new class can be created from existing class, which is called as inheritance. Advantage of inheritance is reusability of the code. During inheritance, the class that is inherited is called as base class and the class that does the inheritance is called as derived class.
                      Refer following article for depth explanation  
                        Polymorphism
                          Polymorphism means having more than one form. Polymorphism can be achieved with the help of overloading and overriding concepts. Polymorphism is classified into compile time polymorphism and run time polymorphism.
                          Refer following article for depth explanation
                          Refer the following articles to learn more about OOPS concept.
                          Summary

                          I hope this article is useful for all readers,if you have any suggestion then contact me.





                          Convert DataTable To Generic List In ASP.NET MVC

                          Many times in MVC we need to work with generic list which will be generated from model class ,suppose we are getting data from DataBase in DataTable and thinking to bind view from model class generic list then first we need to convert DataTable into generic list . so let us see how we can achieve this
                          Suppose the model class is EmpModel.cs as below



                          public class EmpModel
                              {
                                  [Display(Name = "Id")]
                                  public int Empid { get; set; }
                                  [Required(ErrorMessage = "First name is required.")]
                                  public string Name { get; set; }
                                  [Required(ErrorMessage = "City is required.")]
                                  public string City { get; set; }
                          
                                  [Required(ErrorMessage = "Address is required.")]
                                  public string Address { get; set; }
                          
                              }

                           Now Class will be look like as follows


                          public List<EmpModel> GetAllEmployees()
                                  {
                                      connection();
                                      List<EmpModel> EmpList =new List<EmpModel>();
                          
                                      SqlCommand com = new SqlCommand("GetEmployees", con);
                                      com.CommandType = CommandType.StoredProcedure;
                                      SqlDataAdapter da = new SqlDataAdapter(com);
                                      DataTable dt = new DataTable();
                                      con.Open();
                                      da.Fill(dt);
                                      con.Close();
                                      //Bind EmpModel generic list using dataRow 
                                      foreach (DataRow dr in dt.Rows)
                                      {
                          
                                          EmpList.Add(
                          
                                              new EmpModel {
                          
                                                  Empid = Convert.ToInt32(dr["Id"]),
                                                  Name =Convert.ToString( dr["Name"]),
                                                  City = Convert.ToString( dr["City"]),
                                                  Address = Convert.ToString(dr["Address"])
                          
                                              }
                                              
                                              
                                              );
                                      }
                          
                                      return EmpList;
                          
                                  }

                          Please refer below similar article  as above
                          Summary
                          I hope this article is useful for all readers. If you have any suggestion then please contact me. 

                          Save DataTable Into ViewState and Bind Gridview Using ASP.Net C#

                          I have read many forum posts regarding how to save a DataTable in Viewstate and display those records in a GridView without saving in the database. In consideration of those requirements I decided to write an article on it. So let us start creating a web application as:
                          1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
                          2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
                          3. Provide the web site a name such as "SaveDataTableInViewsate" or another as you wish and specify the location.
                          4. Then right-click on Solution Explorer - "Add New Item" - Add Web Form.
                          5. Drag and drop one button and three textBoxes onto the <form> section of the Default.aspx page.
                          6. Now the default.aspx page source code will look such as follows.
                          <%@ 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></title>  
                          </head>  
                          <body style="background-color: #0000FF">  
                              <form id="form1" runat="server">  
                              <table style="color: White;margin-top:30px;margin-left:10px">  
                                  <tr>  
                                      <td>  
                                          Author Name  
                                      </td>  
                                      <td>  
                                          Book Name  
                                      </td>  
                                      <td>  
                                          Book Type  
                                      </td>  
                                      <td>  
                                          Publisher  
                                      </td>  
                                  </tr>  
                                  <tr>  
                                      <td>  
                                          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>  
                                      </td>  
                                      <td>  
                                          <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>  
                                      </td>  
                                      <td>  
                                          <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>  
                                      </td>  
                                      <td>  
                                          <asp:TextBox ID="TextBox4" runat="server"></asp:TextBox>  
                                      </td>  
                                  </tr>  
                                  <tr>  
                                      <td>  
                                      </td>  
                                      <td>  
                                      </td>  
                                      <td>  
                                      </td>  
                                      <td>  
                                          <asp:Button ID="AddProduct" runat="server" Style="color: White" Text="Add Product"  
                                              OnClick="AddProduct_Click" BackColor="#999966" />  
                                      </td>  
                                  </tr>  
                              </table>  
                               
                              <div style="margin-left:10px;margin-top:10px">  
                               <asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server" CellPadding="4"  
                                  ForeColor="#333333" GridLines="None">  
                                  <AlternatingRowStyle BackColor="White" />  
                                  <Columns>  
                                      <asp:BoundField HeaderStyle-Width="120px" HeaderText="Author  Name" DataField="AuthorName" />  
                                      <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Name" DataField="BookName" />  
                                      <asp:BoundField HeaderStyle-Width="120px" HeaderText=" Book Type" DataField="BookType" />  
                                      <asp:BoundField HeaderStyle-Width="120px" HeaderText="Publisher" DataField="Publisher" />  
                                  </Columns>  
                                  <EditRowStyle BackColor="#2461BF" />  
                                  <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
                                  <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />  
                                  <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />  
                                  <RowStyle BackColor="#EFF3FB" />  
                                  <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />  
                                  <SortedAscendingCellStyle BackColor="#F5F7FB" />  
                                  <SortedAscendingHeaderStyle BackColor="#6D95E1" />  
                                  <SortedDescendingCellStyle BackColor="#E9EBEF" />  
                                  <SortedDescendingHeaderStyle BackColor="#4870BE" />  
                              </asp:GridView>  
                              </div>  
                              </form>  
                          </body>  
                          </html>  
                          
                          Now switch to design mode, it will be like this.
                           
                          Now switch to the default.aspx.cs code behind file and write the following code to create and save the datatable into viewstate and bind the GridView as:
                              private void AddDefaultFirstRecord()  
                               {  
                                   //creating dataTable   
                                   DataTable dt = new DataTable();  
                                   DataRow dr;  
                                   dt.TableName = "AuthorBooks";  
                                   dt.Columns.Add(new DataColumn("AuthorName", typeof(string)));  
                                   dt.Columns.Add(new DataColumn("BookName", typeof(string)));  
                                   dt.Columns.Add(new DataColumn("BookType", typeof(string)));  
                                   dt.Columns.Add(new DataColumn("Publisher", typeof(string)));  
                                   dr = dt.NewRow();  
                                   dt.Rows.Add(dr);  
                                   //saving databale into viewstate   
                                   ViewState["AuthorBooks"] = dt;  
                                   //bind Gridview  
                                   GridView1.DataSource = dt;  
                                   GridView1.DataBind();  
                               } 
                          
                           Now call the above function at Page Load so that the initial records will be added into the view state and GridView as
                          protected void Page_Load(object sender, EventArgs e)  
                              {  
                                  if (!IsPostBack)  
                                  {  
                                      AddDefaultFirstRecord();  
                                  }  
                              }
                          
                          Now create a function with the following code that will save the records into a data table using view state and will be available to be bound to the GridView as:
                              private void AddNewRecordRowToGrid()  
                                 {  
                                     // check view state is not null  
                                     if (ViewState["AuthorBooks"] != null)  
                                     {  
                                         //get datatable from view state   
                                         DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"];  
                                         DataRow drCurrentRow = null;  
                                
                                         if (dtCurrentTable.Rows.Count > 0)  
                                         {  
                                
                                             for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)  
                                             {  
                                
                                                 //add each row into data table  
                                                 drCurrentRow = dtCurrentTable.NewRow();  
                                                 drCurrentRow["AuthorName"] = TextBox1.Text;  
                                                 drCurrentRow["BrandName"] = TextBox2.Text;  
                                                 drCurrentRow["Warrenty"] =TextBox3.Text;  
                                                 drCurrentRow["Price"] =TextBox4.Text;  
                                
                                
                                             }  
                                             //Remove initial blank row  
                                             if (dtCurrentTable.Rows[0][0].ToString() == "")  
                                             {  
                                                 dtCurrentTable.Rows[0].Delete();  
                                                 dtCurrentTable.AcceptChanges();  
                                
                                             }  
                                
                                             //add created Rows into dataTable  
                                             dtCurrentTable.Rows.Add(drCurrentRow);  
                                             //Save Data table into view state after creating each row  
                                             ViewState["AuthorBooks"] = dtCurrentTable;  
                                             //Bind Gridview with latest Row  
                                             GridView1.DataSource = dtCurrentTable;  
                                             GridView1.DataBind();  
                                         }  
                                     }  
                                 } 
                          
                          Call the function above to add book details in the button click as:
                              protected void AddProduct_Click(object sender, EventArgs e)  
                                {  
                                    AddNewRecordRowToGrid();  
                                } 
                          
                           Now the entire code of the default.aspx.cs page will be such as follows:
                              using System;  
                              using System.Data;  
                              public partial class _Default : System.Web.UI.Page  
                              {  
                                
                                  protected void Page_Load(object sender, EventArgs e)  
                                  {  
                                      if (!IsPostBack)  
                                      {  
                                          AddDefaultFirstRecord();  
                                      }  
                                  }  
                                  protected void AddProduct_Click(object sender, EventArgs e)  
                                  {  
                                      AddNewRecordRowToGrid();  
                                  }  
                                
                                  private void AddDefaultFirstRecord()  
                                  {  
                                      //creating dataTable   
                                      DataTable dt = new DataTable();  
                                      DataRow dr;  
                                      dt.TableName = "AuthorBooks";  
                                      dt.Columns.Add(new DataColumn("AuthorName", typeof(string)));  
                                      dt.Columns.Add(new DataColumn("BookName", typeof(string)));  
                                      dt.Columns.Add(new DataColumn("BookType", typeof(string)));  
                                      dt.Columns.Add(new DataColumn("Publisher", typeof(string)));  
                                      dr = dt.NewRow();  
                                      dt.Rows.Add(dr);  
                                      //saving databale into viewstate   
                                      ViewState["AuthorBooks"] = dt;  
                                      //bind Gridview  
                                      GridView1.DataSource = dt;  
                                      GridView1.DataBind();  
                                  }  
                                  private void AddNewRecordRowToGrid()  
                                  {  
                                      // check view state is not null  
                                      if (ViewState["AuthorBooks"] != null)  
                                      {  
                                          //get datatable from view state   
                                          DataTable dtCurrentTable = (DataTable)ViewState["AuthorBooks"];  
                                          DataRow drCurrentRow = null;  
                                
                                          if (dtCurrentTable.Rows.Count > 0)  
                                          {  
                                
                                              for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)  
                                              {  
                                
                                                  //add each row into data table  
                                                  drCurrentRow = dtCurrentTable.NewRow();  
                                                  drCurrentRow["AuthorName"] = TextBox1.Text;  
                                                  drCurrentRow["BookName"] = TextBox2.Text;  
                                                  drCurrentRow["BookType"] =TextBox3.Text;  
                                                  drCurrentRow["Publisher"] =TextBox4.Text;  
                                
                                
                                              }  
                                              //Remove initial blank row  
                                              if (dtCurrentTable.Rows[0][0].ToString() == "")  
                                              {  
                                                  dtCurrentTable.Rows[0].Delete();  
                                                  dtCurrentTable.AcceptChanges();  
                                
                                              }  
                                
                                              //add created Rows into dataTable  
                                              dtCurrentTable.Rows.Add(drCurrentRow);  
                                              //Save Data table into view state after creating each row  
                                              ViewState["AuthorBooks"] = dtCurrentTable;  
                                              //Bind Gridview with latest Row  
                                              GridView1.DataSource = dtCurrentTable;  
                                              GridView1.DataBind();  
                                          }  
                                      }  
                                  }  
                                
                              } 
                          
                          Now run the application, the page will look as follows: 
                           
                          Now add some details into the textboxes above and click on the Add Book Details button. Then the records that were saved in the DataTable will displayed in the GridView as:
                           
                          Now add another book details. It will be added in the existing one as:
                          Similar to the above you can add n number of records up to the datatable capacity.
                          Note
                          • Do proper validation such as date input values when implementing.
                          Summary
                          From all the examples above we have learned how to save a DataTable into viewstate and display those records into GridView without saving records into the database. I hope this article is useful for all readers. If you have a suggestion then please contact me.

                          Read Word File Contents Using ASP.Net C#

                          Their often is a need to show uploaded Word file contents in a text box. So by considering that requirement I decided to write this article. So let us learn step-by-step how to read a Word file and display its content in a TextBox.
                          Requirements
                          This type of requirement can be the result of various scenarios, the most common are as follows:
                          1. To upload a resume and show the contents in a TextBox as summary.
                          2.  Save that resume contents into the database so later on it is useful for CV or resume parsing.
                          3. In a blog or community website to upload file contents directly into the editor so it becomes faster to edit contents and save it.
                          Now let us see the preceding explanation by creating a sample web application as follows:
                          1. "Start" - "All Programs" - "Microsoft Visual Studio 2010".
                          2. "File" - "New WebSite" - "C#" - "Empty WebSite" (to avoid adding a master page).
                          3. Provide the web site a name such as "ReadWordFilesInFillTextBox" or another as you wish and specify the location.
                          4. Then right-click on the Solution Explorer and select "Add New Item" and Add Web Form.
                          5. Drag and drop two Buttons, a Fileuploader and TextBox control onto the <form> section of the Default.aspx page
                          6. Set TextBox text mode to multiline.
                          Now the default.aspx page source code will looks as follows.

                          <%@ 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>Article by Vithal Wadje</title>  
                          </head>  
                          <body bgcolor="navy">  
                              <form id="form2" runat="server">  
                              <div style="color: White;">  
                                  <h4>  
                                      Article for C#Corner  
                                  </h4>  
                                  <br />  
                                  <table width="100%">  
                                      <tr>  
                                          <td>  
                                              <asp:TextBox ID="TextBox1" TextMode="MultiLine" runat="server" Height="142px" Width="380px"></asp:TextBox><br />  
                                          </td>  
                                      </tr>  
                                  </table>  
                                  <br />  
                                  <table>  
                                      <tr>  
                                          <td>  
                                              <asp:FileUpload ID="FileUpload1" runat="server" />  
                                          </td>  
                                          <td>  
                                              <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />  
                                          </td>  
                                          <td>  
                                              <asp:Button ID="Button1" runat="server" Text="Clear" OnClick="Button1_Click" />  
                                          </td>  
                                      </tr>  
                                  </table>  
                              </div>  
                              </form>  
                          </body>  
                          </html>  
                          
                          Now add the reference for Microsoft.Office.Interop by right-clicking the Solution Explorer to handle the Word file related process. I hope you have done that. The following namespaces are required to work with operations related to Word files:
                              using System.IO;  
                              using Microsoft.Office.Interop.Word;  
                              using System.Text; 
                          
                          Now double-click on the upload button and write the following code:
                              protected void btnUpload_Click(object sender, EventArgs e)  
                                 {  
                                     //createting the object of application class  
                                     Application Objword = new Application();  
                                
                                     //creating the object of document class  
                                     Document objdoc = new Document();  
                                
                                     //get the uploaded file full path  
                                     dynamic FilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
                                
                                     //pass the optional (missing) parameter to API  
                                     dynamic NA = System.Type.Missing;  
                                
                                     //open Word file document   
                              objdoc = Objword.Documents.Open  
                                            (ref FilePath, ref NA, ref NA, ref NA, ref NA,  
                                             ref NA, ref NA, ref NA, ref NA,  
                                             ref NA, ref NA, ref NA, ref NA,  
                                             ref NA, ref NA, ref NA  
                                              
                                             );  
                                             
                                
                                    //creating the object of string builder class  
                                     StringBuilder sb = new StringBuilder();  
                                
                                     for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)  
                                     {  
                                         string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();  
                                
                                         if (Filedata != string.Empty)  
                                         {  
                                             //Append word files data to stringbuilder  
                                             sb.AppendLine(Filedata);  
                                         }  
                                             
                                     }  
                                
                                     //closing document object   
                                     ((_Document)objdoc).Close();  
                                
                                     //Quit application object to end process  
                                     ((_Application)Objword).Quit();  
                                
                                     //assign stringbuilder object to show text in textbox  
                                     TextBox1.Text =Convert.ToString(sb);  
                                 } 
                          
                          Now double-click on the reset button and write the following code:
                              protected void Button1_Click(object sender, EventArgs e)  
                                 {  
                                     TextBox1.Text =string.Empty;  
                                 } 
                          
                          The entire code of the default.aspx.cs will look as in the following:
                              using System;  
                              using System.IO;  
                              using Microsoft.Office.Interop.Word;  
                              using System.Text;  
                                
                                
                              public partial class _Default : System.Web.UI.Page  
                              {  
                                  protected void Page_Load(object sender, EventArgs e)  
                                  {  
                                
                                  }  
                                  protected void btnUpload_Click(object sender, EventArgs e)  
                                  {  
                                      //createting the object of application class  
                                      Application Objword = new Application();  
                                
                                      //creating the object of document class  
                                      Document objdoc = new Document();  
                                
                                      //get the uploaded file full path  
                                      dynamic FilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);  
                                
                                      //pass the optional (missing) parameter to API  
                                      dynamic NA = System.Type.Missing;  
                                
                                      //open Word file document   
                               objdoc = Objword.Documents.Open  
                                             (ref FilePath, ref NA, ref NA, ref NA, ref NA,  
                                              ref NA, ref NA, ref NA, ref NA,  
                                              ref NA, ref NA, ref NA, ref NA,  
                                              ref NA, ref NA, ref NA  
                                               
                                              );  
                                              
                                
                                     //creating the object of string builder class  
                                      StringBuilder sb = new StringBuilder();  
                                
                                      for (int Line = 0; Line < objdoc.Paragraphs.Count; Line++)  
                                      {  
                                          string Filedata = objdoc.Paragraphs[Line + 1].Range.Text.Trim();  
                                
                                          if (Filedata != string.Empty)  
                                          {  
                                              //Append word files data to stringbuilder  
                                              sb.AppendLine(Filedata);  
                                          }  
                                              
                                      }  
                                
                                      //closing document object   
                                      ((_Document)objdoc).Close();  
                                
                                      //Quit application object to end process  
                                      ((_Application)Objword).Quit();  
                                
                                      //assign stringbuilder object to show text in textbox  
                                      TextBox1.Text =Convert.ToString(sb);  
                                  }  
                                
                                  protected void Button1_Click(object sender, EventArgs e)  
                                  {  
                                      TextBox1.Text =string.Empty;  
                                  }  
                              } 
                          
                          Now run the application. The UI will look as follows:
                          In the preceding UI Browse control will be used to select the files from the physical location. On a upload button click, it will read the uploaded Word file and show it in the TextBox. The Clear button will clear the text box contents.
                          Now select the Word file and click on upload, it will show the file contents in the TextBox as follows.
                           
                          Now you have seen how to read Word file contents and put it into a TextBox.
                          Notes
                          • Do a proper validation such as if it has a file or not of the File Upload control when implementing.
                          Summary
                          From all the preceding examples you have learned how to read Word files and fill in a TextBox. I hope this article is useful for all readers, if you have a suggestion then please contact me.

                          www.CodeNirvana.in

                          Protected by Copyscape
                          Copyright © Compilemode