20 May 2013

export gridview to excel,word,pdf and print in asp.net with c#

Default.aspx

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeFile="Default.aspx.cs" Inherits="_Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <br />
    <center>    <asp:Button ID="btn1" runat="server" Text="Export to Excel" OnClick="btn1_Click" />
        <asp:Button ID="Button1" runat="server" Text="Export to Word"
            onclick="Button1_Click"/>
        <asp:Button ID="Button2" runat="server" Text="Export to PDF"
            onclick="Button2_Click"/>
        <input id="Submit1" onclick="window.print()" type="submit" value="Print" /><br />
    <br />
 
    <asp:GridView ID="gv1" runat="server">
    </asp:GridView>
    </center>

</asp:Content>

Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["con"].ToString());

    protected void Page_Load(object sender, EventArgs e)
    {
        con.Open();
        string sql = "select * from Employee_Details";
        SqlCommand cmd = new SqlCommand(sql, con);
        DataSet ds = new DataSet();
        SqlDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = cmd;
        da.Fill(ds);
        gv1.DataSource = ds;
        gv1.DataBind();
    }
    protected void btn1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment; filename=Expport.xls");
        Response.ContentType = "application/ms-excel";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.AddHeader("content-disposition", "attachment; filename=Expport.doc");
        Response.ContentType = "application/ms-word";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {

        Response.AddHeader("content-disposition", "attachment; filename=Expport.pdf");
        Response.ContentType = "application/pdf";
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTextWriter = new HtmlTextWriter(sWriter);
        HtmlForm frm = new HtmlForm();
        gv1.Parent.Controls.Add(frm);
        frm.Attributes["runat"] = "server";
        frm.Controls.Add(gv1);
        frm.RenderControl(hTextWriter);
        // EmpReportGrid.RenderControl(hTextWriter);        
        Response.Write(sWriter.ToString());
        Response.End();
        
    }
}

web.config

<connectionStrings>
<add name="con" connectionString="Data Source=.;Initial Catalog=exp;Integrated Security=true;"/>
</connectionStrings>

Output







nested gridview in asp.net c#

Create Database:

create database nestedgridview


USE [nestedgridview]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Branch](
[id] [int] IDENTITY(100,1) NOT NULL,
[Branch] [varchar](200) NULL,
[sem] [varchar](200) NULL,
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]
GO
SET ANSI_PADDING OFF
GO

USE [nestedgridview]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[teacher](
[id] [int] IDENTITY(100,1) NOT NULL,
[branch] [int] NULL,
[name] [varchar](200) NULL,
[cell] [varchar](200) NULL,
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]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[teacher]  WITH CHECK ADD FOREIGN KEY([branch])
REFERENCES [dbo].[Branch] ([id])
GO

Create Default.aspx

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

<!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">
    <div>
        <center>
            <asp:GridView ID="gv1" runat="server" AutoGenerateColumns="false" CellPadding="4"
                CellSpacing="2" OnRowDataBound="gv1_RowDataBound" DataKeyNames="id">
                <Columns>
                    <asp:TemplateField HeaderText="Nested Gridview">
                        <ItemTemplate>
                            <%# Eval("id")%>---
                            <%# Eval("Branch")%>
                            ---
                            <%# Eval("sem")%>
                            <asp:GridView ID="gv2" runat="server" Width="100%" EnableViewState="false">
                            </asp:GridView>
                        </ItemTemplate>
                    </asp:TemplateField>
                </Columns>
            </asp:GridView>
        </center>
    </div>
    </form>
</body>
</html>

Create Default.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
    SqlCommand cmd = new SqlCommand();
    DataSet ds = new DataSet();
    SqlDataAdapter da = new SqlDataAdapter();
    protected void Page_Load(object sender, EventArgs e)
    {
        string sql = "select * from Branch";
        con.Open();
        cmd = new SqlCommand(sql, con);
        da.SelectCommand = cmd;
        da.Fill(ds);
        con.Close();
        gv1.DataSource = ds;
        gv1.DataBind();
    }
    protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType != DataControlRowType.DataRow) return;
        GridView gv2 = (GridView)e.Row.FindControl("gv2");
        int fid = int.Parse(gv1.DataKeys[e.Row.RowIndex].Value.ToString());
       // DataTable table = new DataTable();
        DataSet ds1 = new DataSet();
        SqlConnection con1 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString());
        using (con1)
        {
           // con.Open();
            string sql1 = "select * from teacher where branch=@fid";
            using (SqlCommand cmd1 = new SqlCommand(sql1, con1))
            {
                using (SqlDataAdapter da1=new SqlDataAdapter(cmd1))
                {
                    cmd1.Parameters.AddWithValue("@fid", fid);
                    da1.Fill(ds1);
                }
            }
        }
        gv2.DataSource = ds1;
        gv2.DataBind();
       // con.Close();
       // ds1.Clear();
    }
    
    
}

web.config

  <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=.;Initial Catalog=nestedgridview;Integrated Security=true;"/>
  </connectionStrings>

Output:

Difference between interface and abstract class

Abstract Class: 
1) An abstract method is created by specifying the abstract type modifier. 
2) An abstract method contains no body. 
3) An abstract method is not implemented by the base class. 
4) An abstract method is automatically virtual. 
5) A derived class must override it. 
6) Abstract class can have modifiers for methods,properties etc., 
7) An abstract class can implement a property. 
8) The abstract modifier cannot be applied to static methods. 
9) Properties can also be abstract. 
10) A class containing abstract methods must be declared as abstract with the abstract specifier. 
11) There can be no objects of an abstract class. 
12) If a derived class doesn't implement all of the abstract methods in the base class, then the derived class must also be specified as abstract. 
13) An abstract class can inherit from a class and one or more interfaces. 
14) An abstract class can implement code with non-Abstract methods. 
15) Abstract class can have constant and fields. 
16) An abstract class can have constructors or destructor's. 
17) An abstract class cannot be inherited from by structures. 
18) An abstract class cannot support multiple inheritance. 
19) If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. 

Interface:
1) Interfaces cannot be instantiated directly. 
2) Interfaces can contain events, method, indexer and properties. 
3) An Interface can contain property definitions. 
4) Interfaces contain no implementation of methods. 
5) Classes and Structs can implement more than one interface. 
6) An Interface can be inherited from by structures. 
7) An interface itself can inherit from multiple interfaces (Interface can support multiple 
inheritance). 
8) An abstract class can implement a property. 
9) If we add a new method to an Interface then we have to track down all the implementations of 
the interface and define implementation for the new method.

Difference between array list and hash table


Array List:

1.Array List is a List 
2.In this we can only add items to the list 
3.Here we Can Add any datatype value,Every item in arraylist is treated as object 
4. ArrayList Key must be numeric.
5. Arraylist is a collection of objects(may be of different types).

Hash Table:

1.Hash Table is a map 
2.Here we can add data with the key 
3.Retrieving by key in Hashtable is faster than retrieving in Arraylist.
4. Hashtable Contain two parameter first is Key and other is Value and in case of Hash Table key may be numeric or Alpha.
5. Hashtable is also collection which takes a key corresponding to each values.

Difference between dll and exe in .net


.DLL
1.Its a Dynamic Link Library.
2.  It can be reused.
3. It can be versioned.
4. It is not self executable.
5. It doesn't have main function.
6.There are many entry points.
7.The system loads a DLL into the context of an existing thread.
8.DLL Can Occupy own memory space it self.
9.Many .dll files may exists in one application.
10.dll can be shared with other applications.

.EXE
1.Its a executable file.
2. It cannot be reused.
3.It cannot be versioned.
4.It is self executable.
5.It will have main.
6.There is only single main entry.
7.When a system launches new exe, a new process is created.
8.The entry thread is called in context of main thread of that process.
9.Only one .exe file exists per application.
10.Exe cannot be shared with other applications.

Differences between Stored Procedures and Functions


  1. Procedure can return zero or n values whereas function can return one value which is mandatory.
  2. Procedures can have input/output parameters for it whereas functions can have only input parameters.
  3. Procedure allows select as well as DML statement in it whereas function allows only select statement in it.
  4. Functions can be called from procedure whereas procedures cannot be called from function.
  5. Exception can be handled by try-catch block in a procedure whereas try-catch block cannot be used in a function.
  6. We can go for transaction management in procedure whereas we can't go in function.
  7. Procedures can not be utilized in a select statement whereas function can be embedded in a select statement.
  8. UDF can be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section where as Stored procedures cannot be.
  9. UDFs that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  10. Inline UDF's can be though of as views that take parameters and can be used in JOINs and other Rowsetoperations.

Stored Procedure

A Stored Procedure is a program (or procedure) which is physically stored within a database. They are usually written in a proprietary database language like PL/SQL for Oracle database or PL/PgSQL for PostgreSQL. The advantage of a stored procedure is that when it is run, in response to a user request, it is run directly by the database engine, which usually runs on a separate database server. As such, it has direct access to the data it needs to manipulate and only needs to send its results back to the user, doing away with the overhead of communicating large amounts of data back and forth.

User-defined Function

A user-defined function is a routine that encapsulates useful logic for use in other queries. While views are limited to a single SELECT statement, user-defined functions can have multiple SELECT statements and provide more powerful logic than is possible with views.
User defined functions have three main categories:
  1. Scalar-valued function - returns a scalar value such as an integer or a timestamp. Can be used as column name in queries.
  2. Inline function - can contain a single SELECT statement.
  3. Table-valued function - can contain any number of statements that populate the table variable to be returned. They become handy when you need to return a set of rows, but you can't enclose the logic for getting this rowset in a single SELECT statement.

Stored Procedure

Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes (compiled code) whenever it is called.

Function

Function is compiled and executed every time when it is called.

Difference:
  • Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  • Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  • Function takes one input parameter it is mandatory but Stored Procedure may take o to n input parameters..
  • Functions can be called from Procedure whereas Procedures cannot be called from Function.
  • Procedure allows SELECT as well as DML(INSERT/UPDATE/DELETE) statement in it whereas Function allows only SELECT statement in it.
  • Procedures can not be utilized in a SELECT statement whereas Function can be embedded in a SELECT statement.
  • Stored Procedures cannot be used in the SQL statements anywhere in the WHERE/HAVING/SELECT section whereas Function can be.
  • Functions that return tables can be treated as another rowset. This can be used in JOINs with other tables.
  • Inline Function can be though of as views that take parameters and can be used in JOINs and other Rowset operations.
  • Exception can be handled by try-catch block in a Procedure whereas try-catch block cannot be used in a Function.
  • We can go for Transaction Management in Procedure whereas we can't go in Function.

Login code using Stored Procedure

login.aspx

    <asp:Panel ID="panel1" runat="server">
        <table>
            <tr>
                <td align="right">
                    <asp:Label ID="lblUid" runat="server" Text="UserName :"></asp:Label>
                </td>
                <td align="left">
                    <asp:TextBox ID="txtUid" runat="server" Height="25px" Width="275px" BorderColor="#666666"
                        BorderStyle="Solid" BorderWidth="1px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="rfvlogin" runat="server" Display="Dynamic" ControlToValidate="txtUid"
                        Text="*" CssClass="err" ValidationGroup="l" />
                </td>
            </tr>
            <tr>
                <td align="right">
                    <asp:Label ID="lblpwd" runat="server" Text="Password :"></asp:Label>
                </td>
                <td align="left">
                    <asp:TextBox ID="txtpwd" runat="server" TextMode="Password" Height="25px" Width="275px"
                        BorderColor="#666666" BorderStyle="Solid" BorderWidth="1px"></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Display="Dynamic"
                        ControlToValidate="txtpwd" CssClass="err" ValidationGroup="l" Text="*" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="left">
                    <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Sign In"
                        ValidationGroup="l" Height="30px" Width="90px" />
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td align="left">
                    Forgot Login Details?&nbsp;<asp:HyperLink ID="hlnkForgottenPassword" runat="server"
                        NavigateUrl="~/ForgotPassword.aspx">Click Here</asp:HyperLink>
                </td>
            </tr>
        </table>
    </asp:Panel>
    <br />
    <br />
    <asp:Label ID="ltrmsg" runat="server" ForeColor="Red" /></p>

login.asp.cs code


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;

public partial class Login : System.Web.UI.Page
{
    BAL bal = new BAL();

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        try
        {
            if (txtUid.Text != null && txtpwd.Text != null)
            {
                if (bal.getUserLoginDetails(txtUid.Text, txtpwd.Text))
                {
                    FormsAuthentication.RedirectFromLoginPage(txtUid.Text, false);
                    Session["UserId"] = txtUid.Text;
                    Response.Redirect("~/User/Welcome.aspx");
                }              
                else
                    ltrmsg.Text = "Invalid Username (or) Password.";
            }
            else
                ltrmsg.Text = "Username & Password cann't be empty";
        }
        catch (Exception ex)
        {
            ltrmsg.Text = ex.Message;
        }
    }
}

BAL.CS

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

/// <summary>
/// Summary description for BAL
/// </summary>
public class BAL
{
    DAL dal = new DAL();
    DataSet ds = new DataSet();

public BAL()
{
//
// TODO: Add constructor logic here
//
}

  public bool getUserLoginDetails(string Uid, string pwd)
    {
        try
        {
            string _sql = "Sp_UserLoginDetails";
            SqlParameter[] par = new SqlParameter[2];
            par[0] = new SqlParameter("@uid", Uid);
            par[1] = new SqlParameter("@pwd", pwd);
            if (dal.getLoginDetails(_sql, par))
                return true;
            else
                return false;
           // string _sql = "SELECT Username FROM TblUserRegistration where Username='" + Uid + "' AND Password='" + pwd + "'";
           // if (dal.getLoginDetails(_sql))
            //    return true;
          //  else
            //    return false;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
  }
DAL.CS

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

/// <summary>
/// Summary description for DAL
/// </summary>
public class DAL
{
   SqlConnection con;
        SqlDataAdapter da = new SqlDataAdapter();
        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        SqlCommand cmd;
        string fname;

        public DAL()
        {
            con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["class"].ToString());
            fname = string.Empty;
        }

public bool getLoginDetails(string _sql, SqlParameter[] sqlparam)
        {
            try
            {
                string Uid;
                con.Open();
                cmd = new SqlCommand(_sql, con);
                cmd.CommandType = CommandType.StoredProcedure;

                foreach (SqlParameter p in sqlparam)
                {
                    cmd.Parameters.Add(p);
                }

                Uid = Convert.ToString(cmd.ExecuteScalar());
                if (Uid.Length > 0)
                {
                    return true;
                }
                else
                    return false;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                con.Close();
            }
        }
       }






15 May 2013

Difference between Primary Key & Unique Key



Primary Key:

i) Can be only one in a table
ii) It never allows null values
iii) Primary Key is unique key identifier and can not be null and must be unique.
iV) Primary key can be made foreign key into another table.
v) By default, Primary key is clustered index and data in the database table is physically organized in the sequence of clustered index.

Unique Key:

i) Can be more than one unique key in one table.
ii) Unique key can have null values, accept only one null value.
iii) Unique key can be null and may not be unique.
iv) In SQL Server, Unique key can be made foreign key into another table.
v) By default, Unique key is a unique non-clustered index.


Define Primary key and Unique key

 CREATE TABLE Employee 
 (
 EmpID int PRIMARY KEY, --define primary key
 Name varchar (50) NOT NULL,
 MobileNo int UNIQUE, --define unique key
 Salary int NULL
 ) 


3 May 2013

random number generator in c#


using System;
using System.Collections.Generic;
using System.Linq;
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)
    {
        string allowedChars = "";
        allowedChars = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,";
        allowedChars += "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,";
        allowedChars += "1,2,3,4,5,6,7,8,9,0,!,@,#,$,%,&,?";

        char[] sep = { ',' };

        string[] arr = allowedChars.Split(sep);

        string passwordString = "";

        string temp = "";

        Random rand = new Random();

        for (int i = 0; i < Convert.ToInt32(10); i++)
        {
            temp = arr[rand.Next(0, arr.Length)];
            passwordString += temp;
        }
        string pwd = passwordString;
    }
}

Output :-
     pwd=f4U!pv?zo&


Send email code in c#.net



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Net.Mail;
using System.IO;
using System.Xml.Linq;

public partial class Mail_Welcome : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
    {
       SendMail(ToAddress);
     }

    protected void SendMail(string str)       //mail method
    {
        var fromAddress = "Mail Id";   // From address

        var toAddress = str;  //str means to address

        const string fromPassword = "Password";  //from password

        string subject = "Mail Subject";  //mail subject

        string body = "Mail Body ";    //mail body

        var smtp = new System.Net.Mail.SmtpClient();
        {
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
            smtp.Timeout = 20000;
        }
        smtp.Send(fromAddress, toAddress, subject, body);
    }
}
}

Send emails in Asp.net sample code



Send emails in asp.net with C# in four easy steps.
Follow this steps to send mail in asp.net

Step1 :- Add maill settings in your configuration section of the web.cofig. The settings should look like this: 

<configuration>
    <system.net>
      <mailSettings>
         <smtp from="mail_id">
            <network host="mail.myDomain.com" port="25" userName="test@myDomain.com" password="myPassword"/>
         </smtp>
      </mailSettings>
   </system.net

Step2 :-Design your .aspx page to look as shown below
image of send mail form with controls laid out
Step3 :-Doube-click the Send button and add the following code

using System.Net.Mail; //this library contains necessary method to send mail

protected void cmdSend_Click(object sender, EventArgs e)
{
    MailMessage mMailMessage = new MailMessage();
    // address of sender
    mMailMessage.From = new MailAddress(txtFrom.Text);
    // recipient address
    mMailMessage.To.Add(new MailAddress(txtTo.Text));
    // Check if the bcc value is empty
    if (txtBcc.Text != string.Empty)
    {
        // Set the Bcc address of the mail message
        mMailMessage.Bcc.Add(new MailAddress(txtBcc.Text));
    }
    // Check if the cc value is empty
    if (txtCc.Text != string.Empty)
    {
        // Set the CC address of the mail message
        mMailMessage.CC.Add(new MailAddress(txtCc.Text));
     } // Set the subject of the mail message
    mMailMessage.Subject = txtSubject.Text;
    // Set the body of the mail message
    mMailMessage.Body = txtBody.Text;
    // Set the format of the mail message body as HTML
    mMailMessage.IsBodyHtml = true;
    // Set the priority of the mail message to normal
    mMailMessage.Priority = MailPriority.Normal;
    // Instantiate a new instance of SmtpClient
    SmtpClient mSmtpClient = new SmtpClient();
    // Send the mail message
    try
    {
        mSmtpClient.Send(mMailMessage);
    }
    catch (Exception ex)
    {
        ;//log error
        lblMessage.Text = ex.Message;
    }
    finally
    {
        mMailMessage.Dispose();
    }

Step4 :-Run the project, fill in the fields and click the Send button.

6 April 2013

What is stored Procedure

Stored Procedure:-Stored procedure is a precompiled object stored in Database.

Creating Stored Procedure:-


create procedure sp1
as
Begin
select * from table1
end

Execute Stored Procedure:-

EXEC sp1