How to Send Gridview Data in Email Body using Windows Form Application

Introduction

In this article, I will show you how to send gridview data in email body using windows form application. I will use visual studio 2012 framework and SQL server 2008 R2 for this demo.

So, before opening visual studio let's create and populate table tblstudent using following script.


EmailDemo database and tblStudent table script


1
2
GO  
CREATE DATABASE EmailDemo;

1
2
3
4
5
6
7
8
create table tblstudent
(
	Name nvarchar(50),
	DOB date,
	Email nvarchar(50),
	Address nvarchar(50),
	Branch nvarchar(50)
)

1
2
3
4
Insert into tblStudent values('John','2/12/2000','[email protected]','London','IT')
Insert into tblStudent values('David','2/12/1995','[email protected]','New york','CS')
Insert into tblStudent values('Sara','2/5/1990','[email protected]','Paris','IT')
Insert into tblStudent values('Maya','2/6/1995','[email protected]','New york','IT')

Step 1: Create Windows form Application project, by using following steps.


  1. Open Visual Studio.
  2. Click on File -> New -> Project.
  3. In this project, I am using C# as a programming language, but you can also choose VISUAL BASIC if you know syntaxes of VB.
  4. Inside new project -> Visual C# -> Windows -> Select 'Windows form Application' -> Name your project as EmailDemo -> Select Ok
  5. login and registration techstudy

Step 2 : After creating windows form application, you will find your project files inside 'solution explorer' on your right hand side.


  1. Open solution explorer
  2. Now double click on Form1.cs.
  3. Look for DataGridView and button control inside toolbox and drag and drop them on Form1.cs respectively.
  4. login and registration techstudy
    login and registration techstudy
  5. Let's changed button text from button to Send email using button properties.

Step 3 : Write following code inside Form1.cs file.


  1. First of all import some namespaces inside Form1.cs file

  2. 1
    2
    3
    using System.Data.SqlClient;
    using System.Net;
    using System.Net.Mail;
    

  3. Bind gridview with student details. Copy and paste following code inside 'public partial class Form1 : Form'

  4.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    private void BindGrid()
            {
                // Here we are binding our gridview with student details
                string constring = @"Data Source=.;Initial Catalog=EmailDemo;Integrated Security=True";
                using (SqlConnection con = new SqlConnection(constring))
                {
                    using (SqlCommand cmd = new SqlCommand("SELECT * FROM tblStudent", con))
                    {
                        cmd.CommandType = CommandType.Text;
                        using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                        {
                            using (DataTable dt = new DataTable())
                            {
                                sda.Fill(dt);
                                dataGridView1.DataSource = dt;
                            }
                        }
                    }
                }
            }
    

  5. Now call BindGrid method on Form load

  6. 1
    2
    3
    4
    5
     public Form1()
            {
                InitializeComponent();
                BindGrid();
            }
    

  7. Email method to send email

  8.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
            public static void Email(string htmlbodyString)
            {
                try
                {
                    MailMessage message = new MailMessage();
                    SmtpClient smtp = new SmtpClient();
                    message.From = new MailAddress("Enter your email id"); // Your email ID
                    message.To.Add(new MailAddress("Enter email id of person whom you want to send email")); // Email you want to send to
                    message.Subject = "Student details";
                    message.IsBodyHtml = true; //making message body as html  
                    message.Body = htmlbodyString;
                    smtp.Port = 587;
                    smtp.Host = "smtp.gmail.com"; //Gmail host  
                    smtp.EnableSsl = true;
                    smtp.UseDefaultCredentials = false;
                    smtp.Credentials = new NetworkCredential("Email Id", "Passeword of your email Id"); // Add credentails
                    smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
                    smtp.Send(message);
                    MessageBox.Show("Email Sent!");
                }
                catch (Exception ex) {
                    MessageBox.Show(ex.Message);
                }
            }
    

  9. getHtmlBody for email body

  10.  1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
     public static string getHtmlBody(DataGridView grid)
            {
                try
                {
                    // Designing Email body
                    string messageBody = "<h4>List of Student Recods: </h4><br><br>";
                    if (grid.RowCount == 0) return messageBody;
                    string htmltblStart = "<table style=\"border-collapse:collapse; text-align:center;\" >";
                    string htmlTableEnd = "</table>";
                    string htmlHeaderRowStart = "<tr style=\"background-color:#56bc8a; color:#ffffff;\">";
                    string htmlHeaderRowEnd = "</tr>";
                    string htmlTrStart = "<tr style=\"color:#555555;\">";
                    string htmlTrEnd = "</tr>";
                    string htmlTdStart = "<td style=\" border-color:#56bc8a; border-style:solid;\">";
                    string htmlTdEnd = "</td>";
                    messageBody += htmltblStart;
                    messageBody += htmlHeaderRowStart;
                    messageBody += htmlTdStart + "Student Name" + htmlTdEnd;
                    messageBody += htmlTdStart + "DOB" + htmlTdEnd;
                    messageBody += htmlTdStart + "Email" + htmlTdEnd;
                    messageBody += htmlTdStart + "Address" + htmlTdEnd;
                    messageBody += htmlTdStart + "Branch" + htmlTdEnd; 
                    messageBody += htmlHeaderRowEnd;
                    
                    for (int i = 0; i <= grid.RowCount - 1; i++)
                    {
                        messageBody = messageBody + htmlTrStart;
                        messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[0].Value + htmlTdEnd; //Name of student 
                        messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[1].Value + htmlTdEnd; //student DOB  
                        messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[2].Value + htmlTdEnd; //student Email   
                        messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[3].Value + htmlTdEnd; //student Address  
                        messageBody = messageBody + htmlTdStart + grid.Rows[i].Cells[4].Value + htmlTdEnd; //student Branch  
                        messageBody = messageBody + htmlTrEnd;
                    }
                    messageBody = messageBody + htmlTableEnd;                
                    return messageBody;  
                }
                catch (Exception ex)
                {
                    return null;
                    
                }
            }
    

  11. Do not forget to add your email id and password on line no. 7, 8 and 16

  12. Now go to Form1.cs UI and double click on send email button and add following code.

  13. 1
    2
    3
    4
    5
    6
       private void button1_Click(object sender, EventArgs e)
            {
                string htmlbodyString = getHtmlBody(dataGridView1); //From here you will get html string  
                Email(htmlbodyString); //Passing html string to Email function.
                
            }
    

Step 4: Press F5 and see result


login and registration techstudy
login and registration techstudy
login and registration techstudy Download Source Code



Popular Posts