Translate This Blog

Problem: Send Gridview in email

Aspx Page




Aspx.cs Page

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }

    // This method is used to bind gridview from database

    protected void BindGridview()
    {
        SqlConnection con = new SqlConnection(@"Data Source=DOTNET-VIRESHD\SQLEXPRESS;Integrated Security=true;Initial Catalog=hh");
        con.Open();
        SqlCommand cmd = new SqlCommand("SELECT TOP 1000 [ID],[FirstName],[LastName],[Department],[Location] FROM T_Employees", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        gvUserInfo.DataSource = ds;
        gvUserInfo.DataBind();
    }
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        Send_Mail();
    }

    // Method Which is used to Get HTML File and replace HTML File values with dynamic values and send mail
  
    private void Send_Mail()
    {
        MailMessage mail = new MailMessage();  
        mail.To.Add("xyz@gmail.com");   
        mail.From = new MailAddress("abcd@gmail.com");

        mail.Subject = "Send Gridivew in EMail";
        mail.Body += "Please check below data <br/><br/>";
        mail.Body += GetGridviewData(gvUserInfo);
        mail.IsBodyHtml = true;
        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential("abcd@gmail.com", "pwd");
        smtp.EnableSsl = true;
        smtp.Send(mail);

    }

    // This Method is used to render gridview control
    public string GetGridviewData(GridView gv)
    {
        StringBuilder strBuilder = new StringBuilder();
        StringWriter strWriter = new StringWriter(strBuilder);
        HtmlTextWriter htw = new HtmlTextWriter(strWriter);
        gv.RenderControl(htw);
        return strBuilder.ToString();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }


If gridview have any ajax control then 


private void DisableAJAXExtenders(Control parent)
    {
        for (int i = 0; i < parent.Controls.Count; i++)
        {
            if (parent.Controls[i].GetType().ToString().IndexOf("Extender") != -1 && parent.Controls[i].ID != null)
            {
                parent.Controls.RemoveAt(i);
                parent.Controls[i].Dispose();
            }
            if (parent.Controls[i].Controls.Count > 0)
            {
                DisableAJAXExtenders(parent.Controls[i]);
            }
        }
    }


Previous
Next Post »

1 comments:

Click here for comments
Unknown
admin
October 17, 2012 at 5:56 AM ×

Thanks all for like my blogs or post

Congrats bro Unknown you got PERTAMAX...! hehehehe...
Reply
avatar
Thanks for your comment