Sunday, March 10, 2013

Asp.net - Send GridView Data through Mail

In this article i will explain how to send GridView data through mail in ASP.net project.

Step 1
Download Northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 2
Attach a Northwind database into MS-SQL server.

Step 3
Create a Web Application and give solution name as SolSendGridViewDatain_Email_ASP..net.

Step 4
Add a Gridview and button control on Page,it is look like this
<div>
    
        <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>

                  <asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="3" EnableModelValidation="True" ForeColor="Black" GridLines="Vertical">
                        <AlternatingRowStyle BackColor="#CCCCCC" />
                         <Columns>
                            <asp:BoundField DataField="FirstName" HeaderText="FirstName" />
                            <asp:BoundField DataField="LastName" HeaderText="LastName" />
                            <asp:BoundField DataField="City" HeaderText="City" />
                        </Columns>
                        <FooterStyle BackColor="#CCCCCC" />
                        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
                        <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
                        <SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
                </asp:GridView>
                <asp:Button ID="btnSendMail" runat="server" Text="Send Mail" OnClick="btnSendMail_Click" />

            </ContentTemplate>
        </asp:UpdatePanel>
           
  
      
    </div>


Click on Image for better View.

Step 5
Add App_Code folder in the solution and add a New Folder inside the App_Code folder and give folder name as ORD,it is look like this



Click on Image for better View.

Step 6
Add a Linq to Sql class,Select the ORD folder,right click on Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this



Click on Image for better View.

Step 7
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this



Click on Image for better View.



Click on Image for better View.

Visual studio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.

Step 8
Create a Employee object that will use LINQ to SQL to map to this table.go to the Server Explorer,select Northwind database,go to the Tables and select Employees table,it is look like this



Click on Image for better View.

Drag and drop Employees table from Server explorer onto the design surface of the O/R Designer,it is look like this



Click on Image for better View.

Step 9
Create a Employee class in App_Code folder for retriving an employee data from database,it is look like this
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for Employee
/// </summary>
public static class Employee
{
    #region Method

    /// <summary>
    /// Get Employee Data
    /// </summary>
    /// <returns></returns>
    public static IList GetEmployeeData()
    {
        try
        {

            ORD.NorthwindDCDataContext DC = new ORD.NorthwindDCDataContext();

            //// Using Linq
            //return (from Q in DC.Employees
            //        select new
            //        {
            //            FirstName = Q.FirstName,
            //            LastName = Q.LastName,
            //            City = Q.City
            //        }).ToList();
            
            //// Using Lambda Expression
            return DC.Employees.Select(LE => new { FirstName = LE.FirstName, LastName = LE.LastName, City = LE.City }).ToList();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

    #endregion
}

Step 10
Bind Employee data to GridView,it is look like this
protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (IsPostBack == false)
            {
                BindGridView();
            }
        }
        catch (Exception Ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('" + Ex.Message + "');", true);
        }
    }

 /// <summary>
    /// Bind Grid View Data
    /// </summary>
    private void BindGridView()
    {
        try
        {
            IList IListObj = Employee.GetEmployeeData();

            if (IListObj != null)
            {
                if (IListObj.Count >= 1)
                {
                    gvEmployee.DataSource = IListObj;
                    gvEmployee.DataBind();
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }

Step 11
In Code Behind,Write ControlContentToHTML function it is look like this
/// <summary>
    /// Output of Server Control Contents
    /// </summary>
    /// <param name="GvObj"></param>
    /// <returns>String</returns>
    private String ControlContentToHTML(GridView GvObj)
    {
        try
        {
            StringBuilder SB = new StringBuilder();
            StringWriter SW = new StringWriter(SB);
            HtmlTextWriter HTW = new HtmlTextWriter(SW);

            GvObj.RenderControl(HTW);

            return SB.ToString();

            
        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message); 
        }
    }


RenderControl method implementation, which receives any control and returns its HTML string representation.

Step 12
Override the VerifyRenderingInServerForm Method,it is look like this
public override void VerifyRenderingInServerForm(Control control)
    {
        // base.VerifyRenderingInServerForm(control);
        return;
    }

Above override method Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.if we does not override this above function then it will throw exception at run time.

Error: Control 'gvEmployee' of type 'GridView' must be placed inside a form tag with runat=server.

Step 13
In Code Behind,write SendDataToMail function,it is look like this
/// <summary>
    /// Send a mail 
    /// </summary>
    /// <param name="UserName">Specify the User Name</param>
    /// <param name="Password">Specify the Password</param>
    /// <param name="To">Specify the email address of recipient</param>
    /// <returns>Boolean</returns>
    private Boolean SendDataToMail(String UserName,String Password,String To)
    {
        Boolean Flag = false;
        try
        {
            MailMessage MailMsgObj = new MailMessage(UserName,To);
            MailMsgObj.Subject = "GridView Data";

            MailMsgObj.Body = "Dear Friends.<br/><br/>";
            MailMsgObj.Body += ControlContentToHTML(gvEmployee);
            MailMsgObj.Body += "<br/><br/>";
            MailMsgObj.Body += "Thanks & Regards <br/>";
            MailMsgObj.Body += "Kishor Naik";

            MailMsgObj.IsBodyHtml = true;

            SmtpClient SmtpClntObj = new SmtpClient();
            SmtpClntObj.Host = "smtp.gmail.com";
            SmtpClntObj.Port = 587;
            SmtpClntObj.EnableSsl = true;

            SmtpClntObj.Credentials = new System.Net.NetworkCredential(UserName, Password);

            SmtpClntObj.Send(MailMsgObj);

            Flag = true;

        }
        catch (Exception Ex)
        {
            throw new Exception(Ex.Message);  
        }

        return Flag;
    }


Step 14
On btnSendMail_Click event call SendDataTomail function,it is look like this
protected void btnSendMail_Click(object sender, EventArgs e)
    {
        try
        {
            if (SendDataToMail("kishor.naik011.net@gmail.com", "!@#$%^&*()", "kishor.naik011.net@gmail.com"))
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('Data has been sent');", true);
            }
        }
        catch (Exception Ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", "alert('" + Server.HtmlEncode(Ex.Message).Replace("'", "\\'") + "')", true);
        }
    }


Run the Project.

Output


Click on Image for better View.


Click on Image for better View.

Download
Download Source Code

1 comment:

  1. hi kishor.could u add video instead of screen shots.

    ReplyDelete