Thursday 31 March 2011

Avoid insertion of duplicate record using Asp.Net Using Classes


Introduction
In this article, i will discuss about avoid duplicate Records insertion with GridView in ASP.NET.Most of times, when we are play with data and gridview in ASP.NET, we may needs to insert records into the database,when users enter in grdiview.so this time user may enter duplicate records twice times.so this article help you all how to avoid duplicate records insert in to the database from presentation layer to database.
Implementation
Firsy design page like following, 

HTML Code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Duplicate.aspx.cs" Inherits="WebApplication1.Duplicate" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <table style="width: 32%; height: 51px;">
        <tr>
            <td>
                Enter Class
            </td>
            <td>
                <asp:TextBox ID="txt_class" runat="server"></asp:TextBox>
            </td>
            <td>
                <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_class"
                    ErrorMessage="Required"></asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:Button ID="btn_submit" runat="server" Text="Submit" OnClick="btn_submit_Click" />
            </td>
            <td>
                &nbsp;
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <asp:Label ID="lbl_msg" runat="server" ForeColor="Red"></asp:Label>
            </td>
        </tr>
    </table>
    <br />
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
        CellPadding="4" ForeColor="#333333" GridLines="None" Width="554px" OnPageIndexChanging="GridView1_PageIndexChanging"
        OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowDeleting="GridView1_RowDeleting"
        OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound">
        <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
        <RowStyle BackColor="#E3EAEB" />
        <Columns>
            <asp:TemplateField HeaderText="Click On Class to Add Terms">
                <EditItemTemplate>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Required"
                        ControlToValidate="txt_eclass" ValidationGroup="a"></asp:RequiredFieldValidator>
                    <asp:Label ID="lbl_edit" runat="server" Text='<%# Eval("id") %>' Visible="False"></asp:Label>
                    <asp:TextBox ID="txt_eclass" runat="server" Text='<%# Eval("class") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lbl_id" runat="server" Text='<%# Eval("id") %>' Visible="False"></asp:Label>
                    <a href='AdminTerms.aspx?clsid=<%#Eval("id") %>'>
                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("class") %>'></asp:Label></a>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Edit">
                <EditItemTemplate>
                    <asp:LinkButton ID="LinkButton2" runat="server" CommandName="update" ValidationGroup="a">Update</asp:LinkButton>
                    &nbsp;<asp:LinkButton ID="LinkButton3" runat="server" CausesValidation="False" CommandName="cancel">Cancel</asp:LinkButton>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit" CausesValidation="False">Edit</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Delete">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton4" runat="server" CommandName="delete" CausesValidation="False"
                        OnClientClick="return confirm('Correspond to this Class all Sub-Records will be deleted')">Delete</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
        <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
        <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
        <EditRowStyle BackColor="#7C6F57" />
        <AlternatingRowStyle BackColor="White" />
    </asp:GridView>
    </form>
</body>
</html>
In above GUI is very simple and just allow to gridview add/ edit data with gridview directly, then save into the database.
Prepare Stored Procedures
SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbClasses_AdminGrdData]') AND type in (N'P', N'PC'))

BEGIN

EXEC dbo.sp_executesql @statement = N'

-- It will display the data from tbClasses in Admin area.

CREATE PROCEDURE [dbo].[tbClasses_AdminGrdData]
   

AS

      Select * from tbClasses order by class desc

      RETURN
'

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbClasses_AdminClsCHK]') AND type in (N'P', N'PC'))

BEGIN

EXEC dbo.sp_executesql @statement = N'


-- It will avoid to save the duplicate class

CREATE PROCEDURE [dbo].[tbClasses_AdminClsCHK]

      @class varchar(20)

AS

      select class from tbClasses where  class=@class

      RETURN

'

END

GO

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tbClasses]') AND type in (N'U'))

BEGIN

CREATE TABLE [dbo].[tbClasses](

      [id] [bigint] IDENTITY(1,1) NOT NULL,

      [class] [varchar](50) NOT NULL,

 CONSTRAINT [PK_tbClasses_1] PRIMARY KEY CLUSTERED

(

      [id] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

END
In above sql script  is used for this sample project only.when you are use this technique in your project, then you have created own procedures for your project database.
Now write server side code to perform data access operation.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace Admin_Class_Subjects
{
    // Main Class for MAIN_CONNECTION

    public class Main_con
    {
        protected SqlConnection con = new SqlConnection();
        public SqlCommand cmd;
        public SqlDataAdapter adp = new SqlDataAdapter();
        public DataSet ds = new DataSet();
        public Main_con()
        {
            try
            {
                con.ConnectionString = ConfigurationManager.ConnectionStrings["cnn"].ConnectionString;
                con.Open();
            }
            catch
            {
                if (con.State == ConnectionState.Closed)
                {
                    con.Open();
                }
            }
        }
    }

    // Common Method for all Web Form.

    public class common : Main_con
    {
        public DataSet getdataset(SqlCommand cmd)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            adp.SelectCommand = cmd;
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            try
            {
                adp.Fill(ds);
            }
            finally
            {
                adp.Dispose();
                con.Close();

            }


            return ds;
        }
        public DataTable getdatable(SqlCommand cmd)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            adp.SelectCommand = cmd;
            adp.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataTable dt = new DataTable();
            try
            {
                adp.Fill(dt);
            }
            finally
            {
                adp.Dispose();
                con.Close();
            }
            return (dt);
        }

        public DataSet search(String query, String from, String to)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }

            adp = new SqlDataAdapter(query, con);
            adp.SelectCommand.Parameters.Add("@from", SqlDbType.DateTime).Value = from;
            adp.SelectCommand.Parameters.Add("@to", SqlDbType.DateTime).Value = to;
            DataSet ds = new DataSet();
            ds.Clear();
            try
            {
                adp.Fill(ds);
                adp.Dispose();
            }
            catch { }
            finally
            {
                con.Close();
            }
            return ds;

        }



        public SqlDataReader dd_list(String query)
        {

            if (con.State == ConnectionState.Closed)
            {

                con.Open();

            }
            cmd = new SqlCommand();
            cmd.CommandText = query;
            cmd.Connection = con;
            try
            {
                SqlDataReader a = cmd.ExecuteReader();
                return a;
            }
            finally
            {
                cmd.Dispose();
                con.Close();
            }

        }



        public SqlDataReader dd_listWithParameters(SqlCommand cmd)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = cmd.ToString();
            cmd.CommandType = CommandType.Text;
            cmd.CommandType = CommandType.StoredProcedure;
            try
            {
                SqlDataReader a = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return a;

            }
            finally
            {
                cmd.Dispose();

            }
        }
    }

    //||***********INTERFACES***********||\\

    //Inteface of table Classes
    public interface Int_tbclasses
    {
        Int32 p_id
        { get; set; }
        String p_class
        { get; set; }
    }

    //||***********PROPERTIES***********||\\
    //Properties of table Classes

    public class P_tbClasses : Int_tbclasses
    {
        private Int32 id;
        private String classes;
        #region Int_tbclasses Members
        public int p_id
        {
            get
            {
                return id;
            }
            set
            {
                id = value;
            }
        }

        public string p_class
        {
            get
            {
                return classes;
            }

            set
            {

                classes = value;

            }
        }
        #endregion
    }

    //classes of table Classes
    public class cls_tbClasses : Main_con
    {
        public void save(P_tbClasses p)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand("insert into tbClasses values(@class)", con);
            cmd.Parameters.Add("@class", SqlDbType.VarChar, 50).Value = p.p_class;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
        }
        public void update(P_tbClasses p)
        {
            if (con.State == ConnectionState.Closed)
            {
                con.Open();
            }
            cmd = new SqlCommand("update tbClasses set class=@class where id=@id", con);
            cmd.Parameters.Add("@class", SqlDbType.VarChar, 50).Value = p.p_class;
            cmd.Parameters.Add("@id", SqlDbType.VarChar, 50).Value = p.p_id;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
        }

        public void delete(P_tbClasses p)
        {
            if (con.State == ConnectionState.Closed)
            {

                con.Open();
            }
            cmd = new SqlCommand("delete from tbClasses where id=@id", con);
            cmd.Parameters.Add("@id", SqlDbType.VarChar, 50).Value = p.p_id;
            cmd.ExecuteNonQuery();
            cmd.Dispose();
            con.Close();
        }
    }
}
Note:Above data access layer code, i'm not implement proper excption handling and proper data access object dispose.becuase my concern is prevent duplicarte insert into the database.so please do the proper data access code in your project.
Now let me write c# code for page to access gridview and pass data from page to dataaccess layer to insert to the database.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;

public partial class Admin_AdminClass : System.Web.UI.Page
{
    String Query;
    SqlCommand cmd;
    DataTable dt;

    Admin_Class_Subjects.cls_tbClasses tbclasses = new Admin_Class_Subjects.cls_tbClasses();
    Admin_Class_Subjects.P_tbClasses prp = new Admin_Class_Subjects.P_tbClasses();
    Admin_Class_Subjects.common qry = new Admin_Class_Subjects.common();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            grdview();
        }

    }

    protected void btn_submit_Click(object sender, EventArgs e)
    {

        //It will avoid to save the duplicate class

        //Query = "select class from tbClasses where class=@class";

        Query = "tbClasses_AdminClsCHK";
        cmd = new SqlCommand(Query);
        cmd.Parameters.AddWithValue("@class", txt_class.Text);
        dt = qry.getdatable(cmd);
        String a;
        if (dt.Rows.Count == 0)
        {
            try
            {
                a = (dt.Rows[0]["class"]).ToString();
                //It will avoid to save the duplicate class using Comparing string
                if (String.Compare(a.ToUpper(), txt_class.Text.ToUpper()) == 0)
                {
                    lbl_msg.Text = "";
                    prp.p_class = txt_class.Text.Trim();
                    tbclasses.save(prp);
                    grdview();
                    txt_class.Text = "";
                }
            }
            catch
            {

                lbl_msg.Text = "";
                prp.p_class = txt_class.Text.Trim();
                tbclasses.save(prp);
                grdview();
                txt_class.Text = "";
            }
        }
        else
        {

            lbl_msg.Text = "Class already exists";
            txt_class.Text = "";
            return;
        }
    }
    private void grdview()
    {

        //It will display the data from tbClasses in Admin area.
        //Query = "     Select * from tbClasses";
        Query = "tbClasses_AdminGrdData";
        cmd = new SqlCommand(Query);
        dt = qry.getdatable(cmd);
        if (dt.Rows.Count == 0)
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
        else
        {
            GridView1.DataSource = dt;
            GridView1.DataBind();
        }
    }

    protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        grdview();
    }

    protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        GridView1.EditIndex = -1;
        grdview();
    }
    protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
    {
        GridView1.EditIndex = e.NewEditIndex;
        grdview();
    }

    protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Int32 id;
        id = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("lbl_id"))).Text);
        prp.p_id = id;
        tbclasses.delete(prp);
        GridView1.EditIndex = -1;
        grdview();
    }
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        Int32 ID;
        String cls;
        cls = ((TextBox)(GridView1.Rows[e.RowIndex].FindControl("txt_eclass"))).Text;
        ID = Convert.ToInt32(((Label)(GridView1.Rows[e.RowIndex].FindControl("lbl_edit"))).Text);
        prp.p_id = ID;
        prp.p_class = cls.Trim();
        tbclasses.update(prp);
        GridView1.EditIndex = -1;
        grdview();
    }
}

 Connectionstring
<add name="cnn" connectionString="Data source=comp4;database=db_fantasy;uid=sa;pwd=1234;Min Pool Size=100;Max Pool Size=1000;Connect Timeout=10"/>

That's all. through this article, i discussed,how to prevent the duplicate records insert into the database.this is very striaght forward and easy to understand.
Conclusion
In this article, i discussed about avoid duplicate Records insertion with GridView in ASP.NET.if you have any comments, please post ,try to improve my next article.

Dynamically bind dropdown with months names


Introduction
Through this article, i will show to how to Bind item Dynamically to Dropdownlist in ASP.NET.
Implementation
Just place a drop downlist into your web page, then add  following code to bind items to dropdown list within the page load event.
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack )
        {
            DD_Monthbind();
        }
    }

    private void DD_Monthbind()
    {
        DateTimeFormatInfo info = DateTimeFormatInfo.GetInstance(null);
        for (int i = 1; i < 13; i++)
        {       
            DropDownList1.Items.Add(new ListItem(info.GetMonthName(i), i.ToString()));       

        }
    }
}
 
 In above code, i just get the datetime format for the current culture, and then add month names to dropdown list.this is simple snippets, but most usefull.thank for reading.

Search City in asp.net Using google map


Introduction
 In this article, i will show to you how to search city map using Google map in ASP.NET.When you are see now days all the web contacts address are attached with map of the city. the Google has been provided a incredible map service to find the address, zipcode, state through the external web application. So we will implement a web application like find the address with Google map in asp.net.
Implementation
Create a web application project using visual studio and then add following html code in your default page.
<table width="300px" cellpadding="2" cellspacing="2" style="border: 1px solid maroon;">
                <tr>
                    <td colspan="2">
                        &nbsp;<b>Search Your City Map By Adding  City, State and ZipCode FRom Google Map</b>
                    </td>
                </tr>
          
                <tr>
                    <td>
                        City
                    </td>
                    <td>
                        <asp:TextBox ID="txtCity" runat="server">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        State
                    </td>
                    <td>
                        <asp:TextBox ID="txtState" runat="server">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                        ZipCode
                    </td>
                    <td>
                        <asp:TextBox ID="txtZipCode" runat="server">
                        </asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td>
                    </td>
                    <td>
                        <asp:Button ID="ButtonSearch" runat="server" Text="Search" OnClick="ButtonSearch_Click" /><br />
                    </td>
                </tr>
            </table>      
The design is finished, now we have to write server side to do the search for address or zipcode to find in google map.
C# Code
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

public partial class Default2 : System.Web.UI.Page
{

    string url;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void ButtonSearch_Click(object sender, EventArgs e)
    {
        try
        {
        
            string city = string.Empty;
            string state = string.Empty;
            string zip = string.Empty;

            StringBuilder queryAddress = new StringBuilder();
            queryAddress.Append("http://maps.google.com/maps?q=");

        

            if (txtCity.Text != string.Empty)
            {
                city = txtCity.Text.Replace(' ', '+');
                queryAddress.Append(city + ',' + '+');
            }

            if (txtState.Text != string.Empty)
            {
                state = txtState.Text.Replace(' ', '+');
                queryAddress.Append(state + ',' + '+');
            }

            if (txtZipCode.Text != string.Empty)
            {
                zip = txtZipCode.Text.ToString();
                queryAddress.Append(zip);
            }
            url = queryAddress.ToString();
            Response.Redirect(url, false);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message.ToString(), "Unable to Retrieve Map");
        }
    }
}
that's all. i hope its help to all you attach map with your project.

Email using ASP.NET


Introduction
The Email is important in the web site. When you are create a new website you have to implement in the email sending features as well. So in this article I will explain how to send email using ASP.NET with SMTP.
Implementation
As usual create a simple asp.net web project and then add following html code to design page accept the user input such as subject, to email address, from email address, body.In this demonstration I going to use the sample contact us page email sending.
Note: I have used the required validation controls to make sure subject, to email, body are must enter by users.

Figure:Contact us
HTML Code

<body>
    <form id="form1" runat="server">
        <div>
            <table width="700" border="0" cellpadding="1" cellspacing="1">
                <tr>
                    <td colspan="2" valign="middle">
                        <h2>
                            Contact us</h2>
                    </td>
                </tr>
                <tr>
                    <td width="254" valign="middle">
                        Name:</td>
                    <td width="446" valign="middle">
                        <asp:TextBox ID="txt_name" Width="300px" runat="server" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ControlToValidate="txt_name"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Email Address:</td>
                    <td valign="middle">
                        <asp:TextBox ID="txt_email" runat="server" Width="300px" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator5" runat="server" ControlToValidate="txt_email"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Enter Valid Email Address"
                            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="txt_email"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Phone Number:</td>
                    <td valign="middle">
                        <asp:TextBox ID="txt_phone" Width="300px" runat="server" ></asp:TextBox>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server" ControlToValidate="txt_phone"
                            ErrorMessage="Required"></asp:RequiredFieldValidator>
                        &nbsp;
                        <asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server" ControlToValidate="txt_phone"
                            ErrorMessage="Enter numbers only" ValidationExpression="^\d+$"></asp:RegularExpressionValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Type of Service required:</td>
                    <td valign="middle">
                        <label>
                            <asp:DropDownList ID="dd_select" runat="server" >
                                <asp:ListItem Selected="True">Select type of Service required</asp:ListItem>
                                <asp:ListItem Value="Web Development">Web Development</asp:ListItem>
                                <asp:ListItem Value="Software Development">Software Development</asp:ListItem>
                                <asp:ListItem Value="Graphicd DEsign">Graphicd DEsign</asp:ListItem>
                            </asp:DropDownList>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ControlToValidate="dd_select"
                                ErrorMessage="Required" InitialValue="Select type of Service required"></asp:RequiredFieldValidator>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Estimated Budget</td>
                    <td valign="middle">
                        <asp:DropDownList ID="dd_budget" runat="server" >
                            <asp:ListItem Selected="True">Select your budget</asp:ListItem>
                            <asp:ListItem Value="$500 to $1000">$500 to $1500</asp:ListItem>
                            <asp:ListItem Value="$1500 to $2500">$1500 to $2500</asp:ListItem>
                            <asp:ListItem Value="$2500 to $5000">$2500 to $5000</asp:ListItem>
                            <asp:ListItem Value="$5000 +">$5000 +</asp:ListItem>
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="dd_budget"
                            ErrorMessage="Required" InitialValue="Select your budget"></asp:RequiredFieldValidator>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        Comments:</td>
                    <td valign="middle">
                        <label>
                            <asp:TextBox ID="txt_comment" runat="server" class="textarea" Width="300px" Height="90px"
                                TextMode="MultiLine"></asp:TextBox>
                            <asp:RequiredFieldValidator ID="RequiredFieldValidator6" runat="server" ErrorMessage="Required"
                                ControlToValidate="txt_comment"></asp:RequiredFieldValidator>
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle">
                        How did you hear about us?</td>
                    <td valign="middle">
                        <asp:TextBox ID="txtget_id" Width="300px" runat="server" ></asp:TextBox>
                    </td>
                </tr>
                <tr>
                    <td valign="middle" style="border-bottom: 0;">
                    </td>
                    <td valign="middle" style="border-bottom: 0;">
                        <label>
                            <asp:Button ID="btn_submit" runat="server" Text="Submit" class="btn" OnClick="btn_submit_Click" />
                            <asp:Button ID="btn_reset" runat="server" Text="Reset" class="btn" CausesValidation="false" OnClick="btn_reset_Click" />
                            <br />
                        </label>
                    </td>
                </tr>
                <tr>
                    <td valign="middle" style="border-bottom: 0;">
                        &nbsp;</td>
                    <td valign="middle" style="border-bottom: 0;">
                        &nbsp;<asp:Label ID="lbl_msg" runat="server" ForeColor="Black"></asp:Label>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
We have designed contact us page to send email, now let’s start write code for send email, before that we have to configure the SMTP server to send email through the .NET, for the Microsoft made easy for us, just add the SMTPserver IP Address, port username and password in web.config file as like below,
<appSettings>
            <add key="to" value="bharti222000@yahoo.com"/>
            <add key="from" value="your_email_address_gmail"/>
            <add key="id" value="your_email_address_gmail"/>
            <add key="pswd" value="password of your gmail id"/>
            <add key="port" value="587"/>
            <add key="smtp" value="smtp.gmail.com"/>
      </appSettings>

If you are setup by this way, you don’t need specify settings details to SMTPclient object.ASP.NET automatically pickup configuration.
now write code for send email.
C# code

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
// these nemaespaces are used for email.
using System.Web.Mail;
using System.Net.Mime;
using System.IO;
//this namespace is used for the StringBuilder
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    // here i declared a object of the string builder class
    StringBuilder str_mailer = new StringBuilder();
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        // here i am calling method in which i  am completed coding for the email send.
        sendmail();
        // here i am calling method in which i  am completed coding to blank the all the textboxes.
        clr_rec();
    }
    protected void btn_reset_Click(object sender, EventArgs e)
    {
        // here i am calling method in which i  am completed coding to blank the all the textboxes.
        clr_rec();
    }
    private void clr_rec()
    {
        // In this method completed coding to blank the all the textboxes
        txt_name.Text = "";
        txt_email.Text = "";
        txt_phone.Text = "";
        txt_comment.Text = "";
        txtget_id.Text = "";
        dd_select.SelectedIndex = 0;
        dd_budget.SelectedIndex = 0;
    }
  
    private void sendmail()
    {
        try
        {

            // inside the str_mailer(StringBuilder) i am adding the data that will send through the email.
            // StringBuilder is the best class  to adding the complete string.
             str_mailer.Append(@"<b>Name : </b>  " + txt_name.Text);
             str_mailer.Append(@"\n\n\n\ <b>Email Address : </b>" + txt_email.Text );
             str_mailer.Append(@"<br/><b>Phone No : </b>" + txt_phone.Text);
             str_mailer.Append(@"<br/><b>Type Of Service : </b>" + dd_select.Text );
             str_mailer.Append(@"<br/><b>Estimated Budget : </b>" + dd_budget.Text);
             str_mailer.Append(@"<br/>" + "<b>Comment : </b>" + txt_comment.Text );
             str_mailer.Append(@"<br/>" + "<b>How Did You hear about Us : </b>" + txtget_id.Text);
             //below line m giving  sender's email address  and receiever's email address  that is also mentioned inside the <appSettings></appSettings> in the web.config file
             // and m also giving str_mailer.ToString() , in the str_mailer.ToString() coming  completed message with the html tags
             System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["to"], "Info", str_mailer.ToString());
             //below line m giving  sender's email address and password of that email that is mentioned inside the <appSettings></appSettings> in the web.config file
             System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential(ConfigurationManager.AppSettings["id"], ConfigurationManager.AppSettings["pswd"]);
             //below line m giving  smtp and port no: that is also mentioned inside the <appSettings></appSettings> in the web.config file
            System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtp"], Convert.ToInt32(ConfigurationManager.AppSettings["port"]));
            //System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
            //below m setting some important properties that is necessary to send the email
            mailClient.EnableSsl = true;
            //below property IsBodyHtml in true because inside the stringbuilder am using some HTMl tags
            mail.IsBodyHtml = true;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = mailAuthentication;
            mailClient.Send(mail);
            // when all the process will be completed then a message will be displayed inside the label
            lbl_msg.Text = "Thank you, your enquiry has been sent successfully. We will be in contact with you soon.";
        }
        catch
        {

            
           
                lbl_msg.Text = "Please wait..";
                sendmail();
           
          
        }

    }

}

Note:I'm using here SMTP Configuration.
In above code, just create smtpclient object and then set smtp server settings and user credential to accept the connection client and server.Then compose the email message from users input and call Send() method to  send email to address.
Conclusion
Through this article, you have learned how to send email for contact us operation in web site using asp.net