Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, 3 March 2014

Can we declare an Abstract method in non-abstract class?

Can we declare an Abstract method in non-abstract class?
Ans: No,We can't declare an abstract method in a non abstract class but we can declare an non-abstract method in an abstract class.

Monday, 24 February 2014

Difference between function and method


The programming langauages  have two concepts functions and methods. functions are defined in structural language and methods are defined in object oriented langauge. The difference between both is given below :

Functions
  • Functions have independent existence means they can be defined outside of the class. Ex:- main() function in C, C++ Language
  • Functions are defined in structured languages like Pascal,C and object based language like javaScript
  • Functions are called independently.
  • Functions are self describing unit of code.
 //function main in C
void main()
{
 int a,b,c;
 a=5;
 b=6;
 c=a+b;
 printf("Sum is : %d",c);
}

Methods
  • Methods do not have independent existence they are always defined with in class. Ex:- main() method in C# Language that is defined with in a class
  • Methods are defined in object oriented languages like C#, Java
  • Methods are called using instance or object.
  • Methods are used to manipuate instance variable of a class.
 //method sum in C#
class demo
{
int a,b,c;
public void sum()
{
 a=5;
 b=6;
 c=a+b;
 Console.WriteLine("Sum is : {0}",c);
 }
} 

Difference Between Constant and ReadOnly and Static


Constant and ReadOnly keyword are used to make a field constant which value cannot be modified. Static keyword is used to make members static that can be shared by all the class objects. In this article, I am going to explain the difference among these three.
Constant
  • Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
  • A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.
void Calculate(int Z)
{
 const int X = 10, X1 = 50;
 const int Y = X + X1; //no error, since its evaluated a compile time
 const int Y1 = X + Z; //gives error, since its evaluated at run time
}
  • Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
  • Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly
  • A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
class MyClass
{
 readonly int X = 10; // initialized at the time of declaration
 readonly int X1;
 
 public MyClass(int x1)
 {
 X1 = x1; // initialized at run time
 }
}
  • Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
  • Use the readonly modifier when you want to make a field constant at run time.
Static
  • The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. 
  • This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
class MyClass
{
 static int X = 10;
 int Y = 20;
 public static void Show()
 {
 Console.WriteLine(X);
 Console.WriteLine(Y); //error, since you can access only static members
 }
}

  • If the static keyword is applied to a class, all the members of the class must be static.
  • Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
  • Static constructor can't be parameterized and public. Static constructor is always a private default constructor which is used to initialize static fields of the class.

Interface C#


Interface  

An interface acts as a contract between itself and any class or struct which implements it. It means a class that implement an interface is bound to implement all its members.
Interface has only member’s declaration or signature and implicitly every member of an interface is public and abstract.
For example: The most common use of interfaces is, within SOA (Service Oriented Architecture). In SOA (WCF), a service is exposed through interfaces to different clients. Typically, an interface is exposed to a group of clients which needs to use common functionalities.

interface IStore
{
 void Read();
 void Write();
}
 
interface ICompress
{
 void Compress();
 void Decompress();
}
 
public class Document : IStore, ICompress
{
 #region IStore
 
 public void Read()
 {
 Console.WriteLine("Executing Document's Read Method for IStore");
 }
 
 public void Write()
 {
 Console.WriteLine("Executing Document's Write Method for IStore");
 }
 
 #endregion // IStore
 
 #region ICompress
 
 public void Compress()
 {
 Console.WriteLine("Executing Document's Compress Method for ICompress");
 }
 public void Decompress()
 {
 Console.WriteLine("Executing Document's Decompress Method for ICompress");
 }
 #endregion // ICompress
} 

Interface Features:
  • An interface doesn't provide inheritance like a class or abstract class but it only declare members which an implementing class need to be implement.
  • It cannot be instantiated but it can be referenced by the class object which implements it. Also, Interface reference works just like object reference and behave like as object.
IStore IObjStore = new Document();
ICompress IObjCompress = new Document();
  • It contains only properties, indexers, methods, delegates and events signature.
  • It cannot contains constants members, constructors, instance variables, destructors, static members or nested interfaces.
  • Members of an interface cannot have any access modifiers even public.
  • Implicitly, every member of an interface is public and abstract. Also, you are not allowed to specify the members of an interface public and abstract or virtual.
  • An interface can be inherited from one or more interfaces and can extend another interface.
  • A class that implements an interface can mark any method of the interface as virtual and this method can be overridden by derived classes.
  • Implementing multiple interfaces by a class, sometimes result in a conflict between member signatures. You can resolve such conflicts by explicitly implementing an interface member.
  • It is a good practice to start all interface names with a capital “I” letter.
Where to use Interfaces?

  • Need to provide common functionality to unrelated classes.
  • Need to group objects based on common behaviors.
  • Need to introduce polymorphic behavior to classes since a class can implements more than one interfaces.
  • Need to provide more abstract view to a model which is unchangeable.
  • Need to create loosely coupled components, easily maintainable and pluggable components (like log4net framework for logging) because implementation of an interface is separated from itself.
Disadvantage of Interface:
  • The main issue with an interface is that when you add a new members to its, then you must implement those members within all of the classes which implement that interface.
  • Interfaces are slow as these required extra in-direction to find corresponding method in in the actual class.

Abstract Class C#


Abstract class is a special type of class which cannot be instantiated and acts as a base class for other classes.
Abstract class members marked as abstract must be implemented by derived classes.
The purpose of an abstract class is to provide basic or default functionality as well as common functionality that multiple derived classes can share and override.

For example: A class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. In C#, System.IO.FileStream is an implementation of the System.IO.Stream abstract class.


abstract class ShapesClass
{
 abstract public int Area();
}
class Square : ShapesClass
{
 int side = 0;
 
 public Square(int n)
 {
 side = n;
 }
 // Override Area method 
 public override int Area()
 {
 return side * side;
 }
}
 
class Rectangle : ShapesClass
{
 int length = 0, width=0;
 
 public Rectangle (int length, int width)
 {
 this.length = length;
 this.width = width;
 }
 // Override Area method 
 public override int Area()
 {
 return length * width;
 }
}
Abstract Class Features:
  • An abstract class cannot be instantiated.
  • An abstract class contain abstract members as well as non-abstract members.
  • An abstract class cannot be a sealed class because the sealed modifier prevents a class from being inherited and the abstract modifier requires a class to be inherited.
  • A non-abstract class which is derived from an abstract class must include actual implementations of all the abstract members of parent abstract class.
  • An abstract class can be inherited from a class and one or more interfaces.
  • An Abstract class can has access modifiers like private, protected,internal with class members.But abstract members cannot have private access modifier.
  • An Abstract class can has instance variables (like constants and fields).
  • An abstract class can has constructors and destructor.
  • An abstract method is implicitly a virtual method.
  • Abstract properties behave like abstract methods.
  • An abstract class cannot be inherited by structures.
  • An abstract class cannot support multiple inheritance.
Usage:
  • Need to create multiple versions of your component since version is not a problem with abstract class. You can add properties or methods to an abstract class without breaking the code and all inheriting classes are automatically updated with the change.
  • Need to to provide default behaviors as well as common behaviors that multiple derived classes can share and override.

Boxing and Unboxing


Boxing
Implicit conversion of a value type (int, char etc.) to a reference type (object), is known as Boxing. In boxing process, a value type is being allocated on the heap rather than the stack.

Unboxing
Explicit conversion of same reference type (which is being created by boxing process); back to a value type is known as unboxing. In unboxing process, boxed value type is unboxed from the heap and assigned to a value type which is being allocated on the stack.

Real Life Example
int i = 10;
ArrayList arrlst = new ArrayList();

//ArrayList contains object type value

//So, int i is being created on heap

arrlst.Add(i); // Boxing occurs automatically

int j = (int)arrlst[0]; // Unboxing occurs

Tuesday, 17 December 2013

Separate characters in a string using SPLIT and ARRAY

The SPLIT will separate the characters using a unique character or symbol like + , . @_ - etc. and store values in the ARRAY.

Example :

protected void buttonname_Click(object sender, EventArgs e)
{
string a = It-is-a-demo;

string[] b = a.split('-');  //It will split the characters after each of this special character underscore -

string split1 = b[0];  //It will be stored using the array
string split2 = b[1];  // is will be stored
string split3 = b[2];  // a will be stored
string split4 = b[3];  // demo will be stored

lbllaststring.Text = split4;  //demo will be displayed in the label
}

Monday, 15 July 2013

How to use Substring in Asp.net C#


The Substring method is used to extract the characters from any part of the string.The syntax is

Substring( start_position, num_of_chars_to_grab )

Example:

Substring(0,2)
0 is the starting index of the string
2 is the length or number of characters to be grab or extract.

Example to extract characters form a string using Textbox,Label and Button.

protected void Button1_Click(object sender, EventArgs e)

{

string a = TextBox1.Text.ToString();

string b = a.Substring(2, 2); //Extract 2 characters start from the 2 index position

Label1.Text = b.ToString();

}

Wednesday, 24 April 2013

How to store date and time separately using datetime picker in C#


Click Add New Item --> Select Windows Form --> Click Toolbox --> Select 2 datetime pickers as
dateTimePicker1 and dateTimePicker2.

Right Click on dateTimePicker1 --> Select properties --> Select Format --> Change it to Short .
Similarly Right Click on dateTimePicker2 --> Select properties --> Select Format --> Change it to Time .

Now Add an Button(button1) and name it as Insert.

Now Double click on the button, the coding .cs page will be opened. In that for the button click event write the following code.

private void button1_Click_1(object sender, EventArgs e)
{

datevalue = Convert.ToString(dateTimePicker1.Value);

DateTime tdate = DateTime.Now;

vdate = Convert.ToDateTime(datevalue);

datevalue= vdate.ToString("yyyy-MM-dd");

string timevalue = Convert.ToString(dateTimePicker2.Value);
DateTime vtime = DateTime.Now;

vtime= Convert.ToDateTime(timevalue);

timevalue = string.Format("{0}:{1} {2}", tt.Hour, tt.Minute, tt.Hour > 12 ? "PM" : "AM");

SqlConnection con = new SqlConnection ("Data Source=.\\SQLEXPRESS; Initial Catalog=sampledb;Integrated Security=True");

con.Open();

SqlCommand cmd = new SqlCommand("INSERT INTO TABLENAME (datefield,timefield)
VALUE ('" +datevalue+"','" +timevalue+"')", con); //Create database with fields datefield,timefield

cmd.ExecuteNonQuery();

con.Close();
}

Friday, 19 April 2013

3 - Tier architecture Asp.net C#

The 3- Tier architecture consists of 3 layers.They are
Application Layer or Presentation Layer
Buisness Logic Layer(BLL) or Buisness Access Layer(BAL)
Data Access Layer(DAL)

Application Layer or Presentation Layer

This layer is for contains the UI part.Through this layer only we get the input. FOR EXAMPLE:  In the aspx page textbox , button,etc... are used for getting the input and to display or present the output.

Here i will show an example to insert the username and password using 2 text boxes and a button.Write the following in the "userinsert.aspx" page.

<asp:TextBox ID="txtusername" runat="server"></asp:TextBox>
<asp:TextBox ID="txtpassword" runat="server"></asp:TextBox>
<asp:Button ID="btninsert" runat="server">Insert</asp:Button>

Buisness Logic Layer(BLL) or Buisness Access Layer(BAL) 

This layer acts as a interface between Application layer and Data Access Layer.Here we use this layer to assign the parameters i.e, get and set and other calculations related with the data like insert data, retrieve data and validating the data.

Right click on your project web application---> select add new item ----> select class file in wizard --->give name as userBLL.CS


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Data;

public class userBLL

{

    userDAL DAL;
public userBLL()
{
        DAL = new userDAL(this);
}

    private string _UserName;
    private string _Password;
    

    private string _Mode;
    private string _Procedure;
  


    public string UserName    {
        get
        {
            return _UserName;
        }
        set
        {
            _UserName = value;
        }
    }

    public string Password

    {
        get
        {
            return _Password;
        }
        set
        {
           _Password = value;
        }
    }

   public string Mode

    {

        get
        {
            return _Mode;
        }
        set
        {
           _Mode = value;
        }
    }

    public string Procedure
    {
        get
        {
            return _Procedure;
        }
        set
        {
            _Procedure = value;
        }
    
    }


   public void Insert(string Connect)
    {
        DAL.Insert(Connect);
    }
  }

Data Access Layer(DAL)
This Layer contains methods or procedures to connect with database and to perform insert,update,delete,get data from database based on our input data.
Right click on your project web application---> select add new item ----> select class file in wizard --->give name as userDAL.CS

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

public class userDAL
{

    userBAL BAL;
    SqlConnection Con;
    SqlCommand cmd;

     public userDAL(userBAL BAL1)
    {
     BAL=BAL1;
    }
      public void Connection(string Conn)
    {
        Con = new SqlConnection(Conn);
        if (Con.State == ConnectionState.Closed)
        {
            Con.Open();
        }
    }
    public void Insert(string Connect)
    {
        Connection(Connect);
        cmd = new SqlCommand(BAL.Procedure, Con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = BAL.UserName;
        cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = BAL.Password;     
        cmd.Parameters.Add("@Mode", SqlDbType.VarChar).Value = BAL.Mode;
        cmd.ExecuteNonQuery();
        Con.Close();
    }
}

Now BLL and DAL are ready.Now once again return to the application layer and write the following in the button click event of the "userinsert.aspx.cs" page.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
string Conne = ConfigurationManager.ConnectionStrings["Connects"].ConnectionString.ToString();
    userBAL BAL = new userBAL();

  protected void Button1_Click(object sender, EventArgs e)
    {
        BAL.UserName =txtusername.Text;
        BAL.Password = txtpassword;
        BAL.Mode = "Insert"; //Stored procedure for insert
        BAL.Procedure = "SP_Tbl_userinsesrt"; //Stored procedure name 

        BAL.Insert(Conne);
    }

Thats it..3 Layers are completed.Now its ready to run....


Friday, 15 March 2013

UPLOADING AND DOWNLOADING THE PDF FILES FROM THE DATABASE


CREATE TABLE [dbo].[books]
(
[ID] [int] IDENTITY(1,1) NOT NULL,
[Pdlfiles] [varbinary](max) NULL,
[File name] [varchar](max) NULL
)

CREATE A PAGE FOR UPLOADING PDF AS addpdf.aspx AND ADD THE FOLLOWING
         <label>PDF FILE</label>
         <asp:TextBox ID="txtauthor" runat="server"></asp:TextBox>
         <br />
         <label>FILE NAME</label>
         <asp:FileUpload ID="fileupldsample" runat="server" />
         <br />
         <asp:Button ID="btnupload" runat="server" Text="Upload" onclick="btnupload_Click" />

   
IN THE  addpdf.aspx.cs PAGE  ADD THE FOLLOWING
// This namespace should be there
using System.IO;
 protected void btnupload_Click(object sender, EventArgs e)
 {
if(fileupldsample.HasFile)
{
Stream fs = default(Stream);
fs = fileupldsample.PostedFile.InputStream;
BinaryReader br = new BinaryReader(fs);
byte[] pdfbytes = br.ReadBytes(fileupldsample.PostedFile.ContentLength);
SqlCommand cmd = new SqlCommand("insert into tablename",);
}
 }

Tuesday, 12 March 2013

PASSING VALUE FROM ONE FORM TO ANOTHER USING C#


This an example of transferring a value from Form1 to Form2..

IN THE FORM1 TYPE THE FOLLOWING CODE


   public partial class Form1 : Form
    {
        public Form1()
        {

            InitializeComponent();
         }

        public static string Sno;  //Declaring a Global variable ID

    private void button1_Click(object sender, EventArgs e)
        {

         Sno = textBox1.Text;    //Type any value in the textbox and click the button
         Form2 f2 = new Form2();
         f2.Show();
        }
      }

IN THE FORM2 TYPE THE FOLLOWING CODE

  public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
         }

  private void Form2_Load(object sender, EventArgs e)
        {

          int v1 =  int.Parse(Form1.Sno);  //Getting the Sno value from Form1
          Label1.Text  = Sno.ToString();  //Displaing the Sno value got from Form1
        }
     }

Sunday, 10 March 2013

HOW TO CALCULATE COLUMN TOTAL IN DATAGRIDVIEW USING C#


// POPULATE THE DATAGRIDVIEW AND THEN INCLUDE THE FOLLOWING CODE IN ANY EVENT.HERE I AM USING IT IN A BUTTON CLICK EVENT.
private void button1_Click(object sender, EventArgs e)
{

int Total = 0;

for (int i = 0; i < dataGridView1.Rows.Count; i++)

{

Total += Convert.ToInt32(dataGridView1.Rows[i].Cells["Columnname"].Value);

}

textBox1.Text = Total.ToString();
}

Wednesday, 28 November 2012

GRIDVIEW MAIL USING ASP.NET C#

 IN THE ASPX PAGE

  <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server">
       </asp:GridView>
    </div>
        <asp:Button ID="btnSendMail" runat="server" Text="Send Gridview Mail"
        onclick="btnSendMail_Click" Width="123px" />
    <br />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    </form>

IN THE ASXP.CS PAGE
//Name space to be used
using System;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Net.Mail;
using System.Text;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

public partial class Default : System.Web.UI.Page
{
    static string strcon = ConfigurationManager.ConnectionStrings["SQLCON"].ConnectionString;
    //create new sqlconnection and connection to database by using connection string from web.config file
    SqlConnection con = new SqlConnection(strcon);

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

    // This method is used to bind gridview from database
    protected void BindGridview()
    {
      
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from tablename", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        GridView1.DataSource = ds;
        GridView1.DataBind();
    }
//Send mail button click event
    protected void btnSendMail_Click(object sender, EventArgs e)
    {
        string to = TextBox1.Text;//Gets the TO id
        string From = "fromid@gmail.com";
        string subject = "Mark Detail";
        string Body = "HI ,<br>  Check d Attachment <br><br>";
        Body += GridViewToHtml(GridView1);
        Body += "<br><br>Regards,<br>sathya";
        bool send = send_mail(to, From, subject, Body);
        if (send == true)
        {
            string CloseWindow = "alert('Mail Sent Successfully!');";
            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
        }
        else
        {
            string CloseWindow = "alert('Problem in Sending mail');";
            ClientScript.RegisterStartupScript(this.GetType(), "CloseWindow", CloseWindow, true);
        }

    }
//Mail function
    public bool send_mail(string to, string from, string subject, string body)
    {
        MailMessage msg = new MailMessage(from, to);
        msg.Subject = subject;
        AlternateView view;
        SmtpClient client;
        StringBuilder msgText = new StringBuilder();
        msgText.Append(" <html><body><br></body></html> <br><br><br>  " + body);
        view = AlternateView.CreateAlternateViewFromString(msgText.ToString(), null, "text/html");

        msg.AlternateViews.Add(view);
        client = new SmtpClient();
        client.Host = "smtp.gmail.com";
        client.Port = 587;
        client.Credentials = new System.Net.NetworkCredential("fromid@gmail.com", "fromidpassword");
        client.EnableSsl = true; //Gmail works on Server Secured Layer
        client.Send(msg);
        bool k = true;
        return k;
    }
//calling the html of the gridview
    private string GridViewToHtml(GridView gv)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        gv.RenderControl(hw);
        return sb.ToString();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        //Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
    }
}

Friday, 17 August 2012

MESSAGE BOX IN C#


if (MessageBox.Show(”Do you want to delete?”, “Confirm delete”,MessageBoxButtons.YesNo) == DialogResult.Yes)

{

MessageBox.Show(”Deleted”);

}

Thursday, 16 August 2012

AGE CALCULATION USING DATE OF BIRTH IN C#

DateTime olddate = Convert.ToDateTime(textBox1.Text);

DateTime newdate = DateTime.Now;

TimeSpan ts = newdate - olddate;

int differenceindays = ts.Days;

int differenceinmonths = (differenceindays / 365);

textBox5.Text = differenceinmonths.ToString();

Tuesday, 14 August 2012

AUTO NUMBER GENERATION

OleDbConnection cn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\..\..\database.mdb");

cn.open();

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter("SELECT iif(max(fieldname)=Null,1,max(field name) +1) as [Number] from Tablename", cn);

da.Fill(ds);

if (ds.Tables[0].Rows.Count > 0)
{

textBox1.Text= ds.Tables[0].Rows[0]["Number"].ToString();

}

cn.close();

Monday, 14 May 2012

KEYPRESS EVENT IN C#

private void txt1_KeyPress(object sender, KeyPressEventArgs e)
{

if (e.KeyChar == (char)Keys.Enter)

{

//do something

}
}

Thursday, 10 May 2012

CALCULATION IN TEXTBOX USING Convert.ToInt32 and int.parse

                                USING Convert.ToInt32

private void button1_Click(object sender, EventArgs e)
{
int value1 = Convert.ToInt32(this.textBox1.Text);

int value2 = Convert.ToInt32(this.textBox2.Text);

int value3 = Convert.ToInt32(this.textBox3.Text);

int value4 = (value2-value1) * value3;

 this.textBox4.Text = value4.ToString();

 }

USING  int.Parse
private void button1_Click(object sender, EventArgs e)
{

int value1 =(textBox1.Text);

int value2 = int.Parse(textBox2.Text);

int value3 = int.Parse(label1.Text);

intvalue4 = (value2-value1) * value3;

textBox4.Text = value4.ToString();
}

Friday, 27 April 2012

SENDING EMAIL USING ASP.NET

 protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage msg = new MailMessage();

            msg.From = new MailAddress("fromaddress@gmail.com");

            msg.To.Add(Totestbox.Text);

            msg.Subject = subtextbox.Text;

            msg.IsBodyHtml = true;

            msg.Body = bodytextbox.Text;

            msg.Priority = MailPriority.High;

            SmtpClient client = new SmtpClient("smtp.gmail.com", 587);

            client.UseDefaultCredentials = false;

            client.Credentials = new System.Net.NetworkCredential("fromaddress@gmail.com", "password");

            client.Port = 587;

            client.Host = "smtp.gmail.com";

            client.EnableSsl = true;

            client.Send(msg);
            Label1.Text = "mail sent";
        }
        catch (Exception ex)
        {
            Label1.Text ="mail not sent" + ex.Message ;
        }

    } 
back to top