Monday, 22 June 2015

code for sending a mail on on change of a dropdownlist

Add one drop Down On a page after that add a following code in that code behind file



Source Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList ID="Drop123" runat="server" OnSelectedIndexChanged="DropDownList1" AutoPostBack="True">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>


Code Behind File Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindDropDownList();
        }
    }


    protected void sendemail()
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
            mail.From = new MailAddress("pallavitigerkiller@gmail.com");
            mail.To.Add("p.waghmare@direction.biz");
            mail.Subject = "Test Mail - 1";
            mail.Body = "mail with attachment";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("pallavitigerkiller@gmail.com", "tiger121");
            SmtpServer.EnableSsl = true;
            SmtpServer.Send(mail);
        }

        catch (Exception ex)
        {
            //display exception          

        }
    }

    protected void DropDownList1(object sender, EventArgs e)
    {
        string value = Drop123.SelectedValue;

        if (value == "2")
        {
            sendemail();
        }

    }

    private void BindDropDownList()
    {

        Dictionary<string, string> options = new Dictionary<string, string>();
        options.Add("-1", "Select Option");
        options.Add("1", "test");
        options.Add("2", "dispose");

        Drop123.DataSource = options;
        Drop123.DataTextField = "value";
        Drop123.DataValueField = "key";
        Drop123.DataBind();
    }


}

build the solution and check the output.

No comments:

Post a Comment