Thursday, November 24, 2011

Show excel sheet data in Gridview using C#

Hi All,
   This post show how you can show data of Microsoft Excel Sheet inside a ASP.NET gridview.

The excel sheet in this example is generated by exporting the Northwind Database's Customers table . I have placed the excel sheet  in my D:\ directory and named it as "Test".

The excel sheet looks something like this :





Now on a web page take a ASP.NET GridView Control and and on the Page_load event write this code :


        string F1Name = "D:\\Test.xls";
        string CnStr = ("Provider=Microsoft.Jet.OLEDB.4.0;" + ("Data Source="
        + (F1Name + (";" + "Extended Properties=\"Excel 8.0;\""))));
        DataTable DT = new DataTable();
        OleDbDataAdapter DA = new OleDbDataAdapter("Select * from [Customers$]", CnStr);
       Response.Write("File Accessed!!!!");
        try
        {
            DA.Fill(DT);
            GridView1.DataSource = DT;
            GridView1.DataBind();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
                      

Run the WebPage and see the result as: 







Hope it will be useful.

Thanks,
Nitin Sharma



Wednesday, November 23, 2011

Apply Custom Style to Gridview using Style class and ApplyStyle method

Hi,
  In this post I will apply my own style to the Gridview Control.


1) Add a new page say "GV.aspx" in your asp.net website/web application.


2) Drag and drop  Gridview and a button control from the toolbox on the page.


3) Bind the Gridview on page load event. I have used LINQ to SQL In this example for binding the Gridview.
 The database used is Northwind. The name of LINQ class here is DB and I have added two tables Product and Category.



DBDataContext db = new DBDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
        // Simple LINQ query
        var products = from p in db.Products
                       where p.Category.CategoryName == "Beverages"
                       select p;


        GridView1.DataSource = products;
        GridView1.DataBind();
    }

Note that I have instantiated DataContext class outside the Page Load event making it Global to the page.

4) Now I will create a new style from the Style class and apply it to the Gridview using ApplyStyle() method.On the button Click Event add this piece of code:

    protected void btnStyle_Click(object sender, EventArgs e)
    {
        Style myStyle = new Style();
        myStyle.ForeColor = System.Drawing.Color.Red;
        myStyle.BackColor = System.Drawing.Color.Turquoise;
        myStyle.Font.Bold = true;
        myStyle.BorderStyle = BorderStyle.Solid;
        GridView1.ApplyStyle(myStyle);
    }

5) Run it and click on the button and see the output.Below is the screenshot showing before and after applying style.

Gridview before applying style



Gridview after applying style (Click on Apply Style Button)



That's it..!

Thanks,
Nitin Sharma