Tuesday, 8 April 2014

Gridview Sorting Examples Using ASP.Net

In this article I’m going to explain how to perform sorting in ASP.NET GridView. GridView sorting event is raised when the hyperlink to sort a GridView header column is clicked.

GridViewSortEventArgs is used to perform GridView sorting. There are two properties
SortDirection is used sort the GridView column by ascending and descending order.
SortExpression is just the column name that you need to sort.

          In GridView first we have to set property AllowSorting="true". If we are using BoundFiled or TemplateFiled we have to use SortExpression property to enable header field name to sort on.   
Sample code:

<asp:TemplateField HeaderText="Employee ID" SortExpression="empid"> 
            …
</asp:TemplateField>

          In this demo I have used XML to bind the GridView. But you can use database to bind Gridview.  

Designer source code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Gridview Sorting</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="false"
                 OnSorting="gvEmployee_Sorting" AllowSorting="true">
            <HeaderStyle BackColor="#3E3E3E" Font-Bold="True" Font-Names="cambria"ForeColor="White" />
            <RowStyle Font-Names="Calibri" />
            <Columns>           
                <asp:TemplateField HeaderText="Employee ID" SortExpression="empid">
                    <ItemTemplate>
                        <asp:Label ID="lblEmpID" runat="server" Text='<%#Eval("empid")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Name" SortExpression="name">
                    <ItemTemplate>
                        <asp:Label ID="lblName" runat="server" Text='<%#Eval("name")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Designation" SortExpression="designation">
                    <ItemTemplate>
                        <asp:Label ID="lblDesignation" runat="server"Text='<%#Eval("designation")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City" SortExpression="city">
                    <ItemTemplate>
                        <asp:Label ID="lblCity" runat="server" Text='<%#Eval("city")%>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Country" SortExpression="country">
                    <ItemTemplate>
                        <asp:Label ID="lblCountry" runat="server" Text='<%#Eval("country")%>'/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>   
    </form>
</body>
</html>

C# 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.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }
    protected void BindData()
    {      
        ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
        if (ds != null && ds.HasChanges())
        {
            gvEmployee.DataSource = ds;
            gvEmployee.DataBind();
        }
    }
  
    public SortDirection dir
    {
        get
        {
            if (ViewState["dirState"] == null)
            {
                ViewState["dirState"] = SortDirection.Ascending;
            }
            return (SortDirection)ViewState["dirState"];
        } 
        set
        {
            ViewState["dirState"] = value;
        }

    }

    protected void gvEmployee_Sorting(object sender, GridViewSortEventArgs e)
    {
        BindData();
        DataTable dt = new DataTable();
        dt = ds.Tables[0];
        {
            string SortDir = string.Empty;
            if (dir == SortDirection.Ascending)
            {
                dir = SortDirection.Descending;
                SortDir = "Desc";
            }
            else
            {
                dir = SortDirection.Ascending;
                SortDir = "Asc";
            }
            DataView sortedView = new DataView(dt);
            sortedView.Sort = e.SortExpression + " " + SortDir;
            gvEmployee.DataSource = sortedView;
            gvEmployee.DataBind();
        }
    }
}

send email using Asp.Net with c#

In this article I'm going to explain how to send email in ASP.NET application using C#.
          ASP.NET allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP). Here I’ll explain Namespace, Classes, Properties and Methods which are all used to send mail from ASP.NET application.

Namespace:  

System.Net.Mail
The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.

Classes:

 SmtpClient()
Allows applications to send e-mail by using the Simple Mail Transfer Protocol (SMTP).MailMessage()
MailMessage()
Represents an e-mail message that can be sent using the SmtpClient class.

Properties

Gets or sets the credentials used to authenticate the sender.
EnableSsl:
Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection. 
Gets or sets the name or IP address of the host used for SMTP transactions.
Port :
Gets or sets the port used for SMTP transactions.
UseDefaultCredentials:
Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests.
Gets or sets a value that specifies the amount of time after which a synchronous Send call times out.

 Method:

Dispose():
Sends a QUIT message to the SMTP server, gracefully ends the TCP connection, and releases all resources used by the current instance of theSmtpClient class.
Note
Always call Dispose before you release your last reference to the SmtpClient. Otherwise, the resources it is using will not be freed so the garbage collector can reclaim the memory.

Send(MailMessage):
Sends the specified message to an SMTP server for delivery.

Designer Source Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <table width="600px" align="center">
        <tr>
            <td colspan="2" align="center"><b>Send Mail</b></td>
        </tr>
        <tr>
        <td colspan="2"></td>
        </tr>          
        <tr>
            <td> To </td>
            <td> <asp:TextBox ID="txtToMail" runat="server"></asp:TextBox> </td>
        </tr>
        <tr>
            <td> Subject </td>
            <td> <asp:TextBox ID="txtSubject" runat="server" Width="400">
            </asp:TextBox> </td>
        </tr>
        <tr>
            <td> Message </td>
            <td> <asp:TextBox ID="txtMessage" runat="server" TextMode="MultiLine"
                                Width="400px" Height="200px"></asp:TextBox></td>
        </tr>
        <tr>
            <td> &nbsp;</td>
            <td>
                &nbsp;</td>
        </tr>
        <tr>
            <td colspan="2" align="center"> <asp:Button ID="btnSubmit" runat="server"
                                   OnClick="btnSubmit_Click" Text="Send" /> </td>
        </tr>
        <tr>
        <td colspan="2"><asp:Label ID="lblMsg" runat="server" ></asp:Label> </td>
        </tr>                 
    </table>
    </div>
    </form>
</body>
</html> 

Code Behind:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        MailMessage Msg = new MailMessage();
        Msg.From = new MailAddress("example@gmail.com");
        Msg.To.Add(txtToMail.Text);
        Msg.Subject = txtSubject.Text;
        Msg.Body = txtMessage.Text;
        Msg.IsBodyHtml = true;

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
        NetworkCred.UserName = "example@gmail.com";
        NetworkCred.Password = "Your password";
        smtp.UseDefaultCredentials = true;
        smtp.Credentials = NetworkCred;
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.Send(Msg);
        lblMsg.Text = "Email has been successfully sent..!!";
    }
}