Monday, 9 December 2013

Simple Paging and Sorting on GridView in Asp.net

Simple Paging and Sorting on GridView in Asp.net 


Hi friends,
            In this post i will show you how to do paging and sorting on gridview. 

Step 1: On your aspx page paste the below code:-

<asp:GridView runat="server" ID="gv_records" AllowPaging="True" AllowSorting="True"
        AutoGenerateColumns="False" OnPageIndexChanging="gv_records_PageIndexChanging"
        OnRowDataBound="gv_records_RowDataBound" OnSorting="gv_records_Sorting" PagerStyle-BackColor="Orange" PageSize="8"
        PagerStyle-ForeColor="Black" PagerStyle-Font-Underline="false" PagerSettings-Mode="Numeric" PagerStyle-HorizontalAlign="Center" >
        <Columns>
            <asp:BoundField DataField="CountryCode" HeaderText="CountryCode" SortExpression="CountryCode"
                HeaderStyle-BackColor="Orange" HeaderStyle-ForeColor="Black" HeaderStyle-Font-Underline="false" />
            <asp:BoundField DataField="CountryName" HeaderText="CountryName" SortExpression="CountryName"
                HeaderStyle-BackColor="Orange" HeaderStyle-ForeColor="Black" HeaderStyle-Font-Underline="false" />
        </Columns>
    </asp:GridView>


Step 2: Now on your cs page paste below code above Page_Load

 public string sortingOrder  // For Sort Order
        {
            get
            {
                if (ViewState["sortingOrder"] == null)
                {
                    ViewState["sortingOrder"] = "desc";
                }
                return ViewState["sortingOrder"].ToString();
            }
            set
            {
                ViewState["sortingOrder"] = value;
            }

        }

        public string SortColumn   // For Sort Column
        {
            get
            {
                return (ViewState["SortColumn"] == null ? "CountryCode" : ViewState["SortColumn"].ToString()); // CountryCode is column name
            }
            set
            {
                ViewState["SortColumn"] = value;
            }
        }

        public SortDirection sortDirection   // For Sort Direction
        {
            get
            {
                if (ViewState["sortdirection"] == null)
                {
                    ViewState["sortdirection"] = SortDirection.Ascending;
                    //return SortDirection.Ascending;
                }
                return (SortDirection)ViewState["sortdirection"];//.Descending;
            }
            set
            {
                ViewState["sortdirection"] = value;
            }
        }


Step 3: Now write a method for getting data from database in DataSet.

In my case i have written a method fillgrid() to fill gridview and ExecuteSPDataSet() to get data in DataSet .

protected void fillgrid()
        {
            DataSet ds = ExecuteSPDataSet("usp_getcountry"); // This code is for getting data in DataSet.
// Below code is getting data from DataSet in DataView for sorting and binding to GridView. 
            DataView dv = new DataView(ds.Tables[0]);
            dv.Sort = SortColumn + " " + sortingOrder;
            gv_records.DataSource = dv;
            gv_records.DataBind();
        }


Now we have to call above method in Page_Load so write the below code in Page_Load

 if (!IsPostBack)
            {
                fillgrid();
            }




Now paste the below code:-

 protected void gv_records_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gv_records.PageIndex = e.NewPageIndex;
            fillgrid();
        }

        protected void gv_records_Sorting(object sender, GridViewSortEventArgs e)
        {
            if (sortDirection == SortDirection.Descending)
            {
                sortDirection = SortDirection.Ascending;
            }

            else
            {
                sortDirection = SortDirection.Descending;
            }
            sortingOrder = (sortDirection == SortDirection.Descending) ? "asc" : "desc";


            SortColumn = e.SortExpression;
            
            fillgrid();
        }

        protected void gv_records_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            string imgAsc = @" <img src='../Images/white-triangle-up.png' Width='10px' Height='10px' border='0' title='Ascending' />";
            string imgDes = @" <img src='../Images/white-triangle-down.png'Width='10px' Height='10px' border='0' title='Descendng' />";
            if (e.Row.RowType == DataControlRowType.Header)
            {
                foreach (TableCell cell in e.Row.Cells)
                {
                    if (cell.HasControls())
                    {
                        LinkButton lbl = (LinkButton)cell.Controls[0];
                        if (lbl.Text == SortColumn)
                        {
                            if (sortingOrder == "asc")
                            {
                                lbl.Text += imgAsc;
                            }
                            else
                            {
                                lbl.Text += imgDes;
                            }
                        }
                    }
                }
            }
        }

Everything is done now. Run the application.

Paging:-



Sorting:-





You can download sample code from below link:-

Paging Sorting Example

Please leave your feedback and comments below..!


Saturday, 7 December 2013

User Control in Asp.Net

User Control in Asp.Net


Hi Friendz,
           In this post i will show you how to use user control.

First you have to know what is user control.

In addition to using Web server controls in your ASP.NET Web pages, you can create your own custom, reusable controls using the same techniques you use for creating ASP.NET Web pages. These controls are called user controls.

A user control is a kind of composite control that works much like an ASP.NET Web page—you can add existing Web server controls and markup to a user control, and define properties and methods for the control. You can then embed them in ASP.NET Web pages, where they act as a unit.



Now we will see how to create a user control and use it.

Step 1: Right Click on your Project and add new item a popup will appear. Select  Web User Control and Name it Registration.


Step 2: Open Registration.ascx and paste below code.

<div id="RegUserControl">
    <div id="RegUserControl_header">
        <h1 style="color: Black;">
            Free Registration Form!</h1>
    </div>
    <hr style="margin-top: 0px; margin-left: 1px; width: 223px;" />
    <br />
    <asp:Table ID="Table1" runat="server" Style="margin-left: 5px; color: Black;">
        <asp:TableRow>
            <asp:TableCell>
                    <input type="text" id="txtFirstName" placeholder="First Name" style="width: 94px;font-size:10px;" />
            </asp:TableCell>
            <asp:TableCell>
                    <input type="text" id="txtLastName" placeholder="Last Name" style="width: 94px;font-size:10px;" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell>
                    <select id="ddSelectProfile" style="width: 99px;font-size:10px;">
                        <option value="-1">Select Profile</option>
                        <option value="Trader">Trader</option>
                        <option value="Investor">Investor</option>
                        <option value="Employed">Employed</option>
                    </select>
            </asp:TableCell>
            <asp:TableCell>
                    <select id="ddSelectCity" style="width: 99px;font-size:10px;">
                        <option value="-1">Select City</option>
                        <option value="saab">Las Vegas</option>
                        <option value="mercedes">New York</option>
                        <option value="audi">London</option>
                    </select>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell>
                    <input type="text" id="txtMobPrfix" value="+91" disabled="disabled" style="width: 24px;font-size:10px;" />
                    <input type="text" id="txtMobNo" style="width: 59px;font-size:10px;" placeholder="Phone" />
            </asp:TableCell>
            <asp:TableCell>
                    <input type="text" id="txtEmail" placeholder="Email" style="width: 93px;font-size:10px;" />
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell ColumnSpan="2">
                    <textarea id="txtRequirments" style="width: 198px; height: 35px;font-size:10px;font-family:Arial; resize: none;" placeholder="Please describe Your Requirments."></textarea>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell ColumnSpan="2">
                    <div style="width: 200px; font-size: 10px;font-family: Arial;">
                        <input type="checkbox" id="chkT&C" />I agree to all terms & conditions.<span style="color: red;">*</span></div>
            </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
            <asp:TableCell ColumnSpan="2">
                    <div style="width: 200px; font-size: 10px;">
                        <input type="submit" style="background-color:#11B5E7;border-radius: 5px;-moz-border-radius: 5px;-webkit-border-radius: 5px;color:White;" 
                        id="btnSubmit" value="Submit" /></div>
            </asp:TableCell>
        </asp:TableRow>
    </asp:Table>
</div>
Step 3: Open the page where you want to add user control.After the page tag paste the below code as shown in the image.

<%@ Register TagPrefix="sam" TagName="Label" Src="~/Registration.ascx" %>



Step 4: Now Paste the below code in your MainContent 

 <sam:Label runat="server" ID="Reg_usercontrol" Title="Regestration" />


Now run the project you will see the user control 


Now any where in the project you want this user control just follow Step 3 & Step 4.



You can download sample code from below link:-

User Control Example


Please leave your feedback and comments below..!

Friday, 6 December 2013

AJAX Cascading Dropdown in Asp.NET

AJAX Cascading Dropdown in Asp.NET

Hi Friends,
           In this post i have shown how to use AJAX Cascading Dropdown in Asp.Net. Also added sample Code at the end of the post.

Step 1: Download the ajax toolkit from Ajax Toolkit and extract it.

Step 2: Now open toolbox in Visual Studio then Right Click on it and Add Tab



Now enter tab Name and press Enter Key




Now Right Click on your New tab And Select Choose Items...


A popup box will appear Click on Browse then go to the path where you have extracted AjaxToolkit and select AjaxControlToolkit.dll then press OK



Now you will see the list of ajax tools


Now we are Ready to use Ajax Cascading Dropdown

Now we have to add reference in the project 

Note:- First check references if AjaxControlToolkit is there then no need to add reference Proceed to Step 3


Right Click on References in your project then click Add Reference




A popup box will appear click on browse tab then go to folder where you have extracted ajax toolkit and select AjaxControlToolkit.dll then press OK





Step 3: Now Create a new WebForm and paste the below code


<div>

        <table align="center">

            <tr>

                <td colspan="2">

                    <b>Cascading Dropdown Sample</b>

                </td>
            </tr>
            <tr>
                <td>
                    Select Country:
                </td>
                <td>
                    <asp:DropDownList ID="ddCountry" runat="server" Width="200px">
                    </asp:DropDownList>
                    
                </td>
            </tr>
</table>
</div>

Now Drag and Drop Cascading DropDown From Tool Box Near asp:dropdownlist


Step: 4 Now Right Click on your project and add new item to your project 
then select Web Service and click add button


Step: 5 Open WebService1.asmx.cs and add the name space

using AjaxControlToolkit;

Now paste below code:-


 [WebMethod]

        public CascadingDropDownNameValue[] BindCountry(string knownCategoryValues, string category)

        {

            List<CascadingDropDownNameValue> countrydetails = new List<CascadingDropDownNameValue>();



            countrydetails.Add(new CascadingDropDownNameValue("India", "1"));
            countrydetails.Add(new CascadingDropDownNameValue("USA", "2"));
            countrydetails.Add(new CascadingDropDownNameValue("Germany", "3"));
            countrydetails.Add(new CascadingDropDownNameValue("South Africa", "4"));
            countrydetails.Add(new CascadingDropDownNameValue("Russia", "5"));
            countrydetails.Add(new CascadingDropDownNameValue("China", "6"));
            countrydetails.Add(new CascadingDropDownNameValue("Japan", "7"));
            countrydetails.Add(new CascadingDropDownNameValue("Canada", "8"));
            countrydetails.Add(new CascadingDropDownNameValue("Rome", "9"));
            countrydetails.Add(new CascadingDropDownNameValue("Brazil", "10"));

            return countrydetails.ToArray();
        }

Now your page should look like this:-



Now Un-comment this line:- 

    [System.Web.Script.Services.ScriptService]




Step: 5 Now in cascading dropdown on your web form add the below code after runat="server"

Category="Country"
                    TargetControlID="ddCountry" LoadingText="Loading Countries..." PromptText="Select Country"
                    ServiceMethod="BindCountry" 

after ServiceMethod paste this :- 

 ServicePath="~/WebService1.asmx"

Now it Should look like this :-



 Step: 6 Now drag and Drop toolkitscriptmanager from toolbox after form tag 


  


Now you are Done Press F5 to start debugging and you will see your dropdown


You can download sample code from below link:-

Cascading Dropdown Example

Please leave your feedback and comments below..!


Thursday, 5 December 2013

How To Transfer Values From One Page To Another Through Query String in Asp.NET

How To Transfer Values From One Page To Another Through Query String in Asp.NET 


Hi Friends,
          In this post i have shown how to transfer values from one page to another through Query String.


Step 1: Create a New Web Form Page1.aspx . Then paste the below code:-



<asp:Label runat="server" ID="lbl" >Text To Transfer to next Page :</asp:Label><asp:TextBox runat="server" ID="txttrans"></asp:TextBox>
    <br />
    <asp:Button runat="server" ID="btnnext" Text="Transfer To Next Page" onclick="btnnext_Click" />



Step 2: Create a New Web Form Page2.aspx . Then paste the below code:-

 <asp:Label runat="server" ID="lbl" >Text Transfered from Previos Page :</asp:Label><asp:TextBox runat="server" ID="txttransfered"></asp:TextBox>


Step 3: Now open Page2.aspx.cs and paste the below code in Page_Load

if (Request.QueryString.Count > 0)
            {
                txttransfered.Text = Request.QueryString["Text"].ToString();
            }


Step 4: Now open Page1.aspx.cs and paste the below code below Page_Load



 protected void btnnext_Click(object sender, EventArgs e)
        {
            string trans = txttrans.Text.Trim();

            Response.Redirect("~/TransferValues/Page2.aspx?Text="+trans);
            // Your second page url where you want to transfer the values
        }


Snaps:-


Now Click Transfer To Next Page



Your Text is transferred. You can see it in Url.


Please leave your feedback and comments below..!


Wednesday, 4 December 2013

How to Send Email with WCF Service in Asp.NET

How to Send Email with WCF Service in Asp.NET

Hi Friends,
            In this post I will tell you Step by Step Process how to send email using WCF Service. I will first explain how to create WCF service then I will try to implement email functionality using WCF Service. Here i am using Gmail to send email., that why user must have gmail account for sending email.


Step:1 Create a new ASP.Net Web Application.
Step:2 Now right click on solution and add new Project.






Step:3 Now form installed templates select WCF then Select wcf service application and name it Email. 






Now you should have two projects in your solution.






Step:4 Now from Email project open IService1.cs add the below namespace

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Net.Mail;


Now Delete the below code:-



and this




Now paste the below code:-

[ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string Email(SendEmail objemail);

    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    
    [DataContract]
    public class SendEmail
    {
        string from, to, cc, bcc, subject, body, filename,path;

        //Stream attachment;

        [DataMember]
        public string From
        {
            get { return from; }
            set { from = value; }
        }

        [DataMember]
        public string To
        {
            get { return to; }
            set { to = value; }
        }

        [DataMember]
        public string Cc
        {
            get { return cc; }
            set { cc = value; }
        }

        [DataMember]
        public string Bcc
        {
            get { return bcc; }
            set { bcc = value; }
        }

        [DataMember]
        public string Subject
        {
            get { return subject; }
            set { subject = value; }
        }

        [DataMember]
        public string Body
        {
            get { return body; }
            set { body = value; }
        }
    }

Now your Page should look like this:-





Step:5 Now open Service1.svc.cs and add below namespace

using System.Net.Mail;
using System.Net;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


Now Delete the below code :-




Now paste the below code:- 

public string Email(SendEmail objemail)
        {
            string fromEmail = "Your Gmail Id";
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(fromEmail, "Your Name");
            mail.Subject = objemail.Subject;
            mail.Body = objemail.Body;

           
            mail.To.Add(objemail.To);
            if (objemail.Cc.ToString() != null && objemail.Cc.ToString() != "")
            {
                mail.CC.Add(objemail.Cc);
            }
            if (objemail.Bcc.ToString() != null && objemail.Bcc.ToString() != "")
            {
                mail.Bcc.Add(objemail.Bcc);
            }

            SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
            smtpClient.UseDefaultCredentials = false;
            smtpClient.EnableSsl = Convert.ToBoolean(true);
            smtpClient.Credentials = new NetworkCredential("Your Gmail Id", "Your Password");
            try
            {
                smtpClient.Send(mail);
                return "Email Send";
            }
            catch
            {
                return "Failed To Send Email";
            }

        }



Note:- Please don't forget to enter your gmail id and password . 

Now Your Page should look like this:-





Step:6 Now Press F6 To build your project.

Then Right Click on Service1.svc and view in browser:-




Now from browser copy the url.




Step:7 Now add service reference in your web application project. In my case my project name is WCFExample. Right Click Reference and Click on Add Service Reference.




Now a popup box will appear. In Address paste the copied url then press Go.
Now in Namespace write EmailService then press OK.


  


Step:8 Now create a new web form using master page and name it Email.aspx

Now Paste below code in main content of Email.aspx page:-

     <div class="entry-content">
        <h2>
            Email</h2>
        <asp:Label runat="server" ID="lblTo">To</asp:Label>
        <asp:TextBox ID="txt_to" runat="server" CssClass="TextBox" AutoComplete="off" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVto" runat="server" ControlToValidate="txt_to"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Please enter email Id."
            ToolTip="Please enter email Id" ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="REVto" ValidationGroup="sbmitbtn" runat="server"
            Display="Dynamic" SetFocusOnError="true" ToolTip="Email Id invalid." ErrorMessage="Email Id invalid."
            ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_to"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label runat="server" ID="lblCC">Cc</asp:Label>
        <asp:TextBox ID="txt_cc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVcc" ValidationGroup="sbmitbtn" Display="Dynamic"
            SetFocusOnError="true" runat="server" ToolTip="Please check email id/id's are wrong."
            ErrorMessage="Please check email id/id's are wrong" ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_cc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label runat="server" ID="lblBcc">Bcc</asp:Label>
        <asp:TextBox ID="txt_bcc" runat="server" AutoComplete="off" CssClass="TextBox" PlaceHolder="eg: sam_01@gmail.com"
            Width="215"></asp:TextBox>
        <asp:RegularExpressionValidator ID="REVBcc" ValidationGroup="sbmitbtn" Display="Dynamic"
            SetFocusOnError="true" runat="server" ToolTip="Please check email id/id's are wrong."
            ErrorMessage="Please check email id/id's are wrong" ValidationExpression="((\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*)*([, ])*)*"
            ForeColor="Red" ControlToValidate="txt_bcc"></asp:RegularExpressionValidator>
        <br />
        <br />
        <asp:Label ID="Label2" class="Label" runat="server">Subject</asp:Label>
        <br />
        <asp:TextBox ID="txt_subject" runat="server" AutoComplete="off" CssClass="TextBox"
            MaxLength="50" Width="215"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVsubject" runat="server" ControlToValidate="txt_subject"
            Display="Dynamic" SetFocusOnError="true" CssClass="failureNotification" ErrorMessage="Subject is required."
            ToolTip="Subject is required." ForeColor="Red" ValidationGroup="sbmitbtn"></asp:RequiredFieldValidator>
        <br />
        <br />
        <label class="Label">
            <asp:Literal ID="Literal1" runat="server" Text="Message"></asp:Literal>
        </label>
        <br />
        <asp:TextBox ID="txt_msgbody" runat="server" TextMode="MultiLine" CssClass="multiline"
            Style="height: 180px; width: 570px; resize: none;" ValidationGroup="sbmitbtn"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RFVmsg" runat="server" ToolTip="Please write in message body."
            CssClass="failureNotification" ErrorMessage="Please write in message body." ControlToValidate="txt_msgbody"
            ValidationGroup="sbmitbtn" ForeColor="Red"></asp:RequiredFieldValidator>
        <br />
        <asp:Button ID="btn_email" CssClass="Button" runat="server" Text="Send" ValidationGroup="sbmitbtn"
            OnClick="btn_email_Click" />
        <br />
        <asp:Label ID="lblemailmsg" runat="server"></asp:Label>
        <asp:HiddenField runat="server" ID="hf_msz" />
    </div>

Now your page should be like:-


Step:9 Now open Email.aspx.cs and add below namespace

using System.IO;
using System.Net.Mail;
using System.Net;
using WCFExample.EmailService; // In my case reference is added in my web appplication project WCFExample

Now Paste the below code above Page_Load:-

EmailService.Service1Client objemail = new EmailService.Service1Client();

Now add below code below Page_Load:-

protected void btn_email_Click(object sender, EventArgs e)
        {
            SendEmail seobj = new SendEmail();

            seobj.To = txt_to.Text.Trim();
            seobj.Cc = txt_cc.Text.Trim();
            seobj.Bcc = txt_bcc.Text.Trim();
            seobj.Subject = txt_subject.Text.Trim();
            seobj.Body = txt_msgbody.Text.Trim();
            
            string result = objemail.Email(seobj);
            lblemailmsg.Text = result;



        }

Now press F6 to build project. Then Press F5 to run the project.

Finally Your page will be like this:-



Enter email-id,subject,message and Press Send Button to send email.
When Email is send you will get message "Email Send" below Send Button.


Please leave your feedback and comments below..!