Popular Posts

Friday, 25 July 2014

CALL WEB-SERVICE THROUGH JQUERY AND AJAX IN ASP.NET

CALL WEB-SERVICE THROUGH J QUERY AND AJAX IN ASP.NET





STEP 1:
First while creating the web services you need to uncomment the below tag in web service.

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

[System.Web.Script.Services.ScriptService]


STEP 2:

Include the scriptManager tag from AJAX EXTENSIONS:

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="~/Service.asmx" />      //the path to your web services
    </Services>
    </asp:ScriptManager>
   


STEP3:

create a simple html button control which will call the javascipt .


Here one textbox is also added that will call the PARAMETERIZED WEB SERICES WEB METHOD FROM JAVASCRIPT ...THAT WILL BE EXECUTED FROM BUTTON CLICK..


   <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="button" onclick="storeinfo();" />
    

STEP 4:  THE JAVASCRIPT:

    <script type="text/javascript">
        function storeinfo() {
            debugger;
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
            function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    
    </script>




EXPLANATION:

    function storeinfo() {
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
    

a)The function storeinfo is called on the button click.
b)the value from textbox is recieved .
c)the Service class is used to call the WEB METHOD
Here in case mine web method is GetStoreData.
d)its has 4 parameters:
pass:  the password accuried from textbox(i.e the webmethod needs one parameter)
storeinfoSuccessCallback : function that is called on sucess on execution
storeinfoFailCallback: function that is called on error of execution
true: user context

A SIMPLE IMPLEMENTATION OF SUCCES AND ERROR FUNCTIONS:

function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    

THE COMPLETE CODE:


<%@ 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>Calling webservice via javascript and ajax</title>
    <script type="text/javascript">
        function storeinfo() {
            debugger;
            var pass = document.getElementById("TextBox1").value;
            Service.GetStoreData(pass, storeinfoSuccessCallback, storeinfoFailCallback, true);
            }
            function storeinfoSuccessCallback(result) { 
            
            alert(result);
            }

            function storeinfoFailCallback(error) {

                alert(error.get_message());
            
            }
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="~/Service.asmx" />      
    </Services>
    </asp:ScriptManager>
    <div>
    enter password: 
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="Button1" type="button" value="button" onclick="storeinfo();" />
    </div>
    </form>
</body>
</html>


AND THAT's IT...........

ENJOY...

Wednesday, 23 July 2014

GET DATA FROM SQLITE AND MYSQL DATABASES

GET DATA FROM SQLITE AND MYSQL DATABASE



Today we will see how to get data from sqlite database and mysql database .

1. DATA FROM SQLITE DATABASE.

To connect sqlite to asp.net we need to download the dll, you can down load the updated dll from the 
web site of sqlite :  http://www.sqlite.org/download.html

OR
Finisar.SQLite
- An ADO.NET Data Provider for SQLite

OR




Put the dll in your bin folder.

NOTE*: check the version of your sqlite and your framework you are using as well as the 32bit or 64 bit dll you need to download as per your application and database.


THE CODE BEHIND PAGE: 
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 Finisar.SQLite;
using System.Data.SQLite;
   using MySql.Data.MySqlClient;

public partial class _Default : System.Web.UI.Page
{
 public static string GetConnectionString()
{
  string connStr = String.Format("server={0};user id={1}; password={2};" + 
    "database=TESTDB; pooling=false", "localhost",
    "root", "youdbpassword");

  return connStr;
}
    protected void Page_Load(object sender, EventArgs e)
    {
        //connection to sqlite database

        System.Data.SQLite.SQLiteConnection cn = new System.Data.SQLite.SQLiteConnection("Data Source=C:/sqlite/testdb.db;Version=3;New=False;Compress=True;"); 
        try
        {

                      cn.Open();
            SQLiteCommand cmd = new SQLiteCommand("select * from emp", cn);
            DataTable dt = new DataTable();
            SQLiteDataAdapter da = new SQLiteDataAdapter(cmd);
            da.Fill(dt);
            GridView1.DataSource = dt;
            GridView1.DataBind();
           
        }
        catch
        {

            //display any exeptions  

        }
        finally
        {
            cn.Close();
        }  
  

    }
}





2.CONNECT TO MYSQL DATABASE:


Download the mysql from oracle site :

Install as the complete type and you will have the connector/dll required to connect to the asp.net .Or else you need to download the connector from the same above site seperate.

the connector location will be :
C:\Program Files (x86)\MySQL\Connector NET 6.8.3\Assemblies\v4.0
in your PC.

INCLUDE THE mysql.data.dll in your application and rest is done...............


            //connection to mysql database
            MySql.Data.MySqlClient.MySqlConnection mycon =
            new MySqlConnection(GetConnectionString());

            if (mycon.State != ConnectionState.Open)
                try
                {
                    mycon.Open();
                    MySqlCommand cmdmysql = new MySqlCommand("select * from empsql", mycon);
                    MySqlDataAdapter damysql = new MySqlDataAdapter(cmdmysql);
                    DataTable dtmysql = new DataTable();
                    damysql.Fill(dtmysql);
                    GridView2.DataSource = dtmysql;
                    GridView2.DataBind();

                }
                catch (MySqlException ex)
                {
                    throw (ex);
                }




Monday, 21 July 2014

Dynamic Masterpage or Adding master page at run time

DYNAMICALLY ADDING MASTER PAGES.


Conditions occurs when we have several master page and need to add on certains pahes at specific conditions.like for some user some master page and others.

so how to add master page at run time.....WHO IS THERE???

..................................................PAGE_INIT Method to rescue................................................................


The Design Page:

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

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
    <p>
        This page loads the ,master page dynamically everytime pages loads among three 
        maser page availables....</p>
</asp:Content>




this is the sample TestMasterPage.aspx where we will add different master pages according to some conditionssss.
here i have taken a random number and adds new master page at every random number.



THREE MASTER PAGES ARE CREATED ......

site.master  :  the default master page in asp.net web application
MasterPage.master  :  Say masterpage for user and clients
MasterPage2.master : say master page for adminsitrator and testing




THE CODE BEHIND FILE:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class TetsmasterPage : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Random r = new Random();
        int i =r.Next(3);
        if (i == 0)
        {
            Page.MasterPageFile = "~/MasterPage.master";
        }
        else if (i == 1)
        {

            Page.MasterPageFile = "~/MasterPage2.master";
        }
        else
        {
            Page.MasterPageFile = "~/Site.master";

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

    }
}



And THAT ALL.......


so put your logic in Pre_Init method and import the conserned master page in the aspx file.







Sunday, 20 July 2014

simple captcha in asp.net

SIMPLE OWNED CAPTCHA TO FOREPLAY BOTS...........



Here is the code for adding a simple captcha in your aspx code rather than using any third party.
use ur imagination and create your own.


THE ASPX PAGE:


<%@ 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">
   
    <p>
        CAPTCHA :</p>
    <p>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> + <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> =
        <asp:TextBox ID="TextBox1" runat="server" Width="40px"></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
    </p>
   
</asp:Content>




Here we have added two lables and one text box to display the number (random ) and to get the result from the user respectively..


THE CODE BEHIND PAGE:


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)
    {
        if (!IsPostBack)
        {
            Random _r = new Random();
            int n = _r.Next(10);
            Label1.Text = "0";
            Label2.Text = n.ToString();
        }

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

        int result = Convert.ToInt32(TextBox1.Text            );
        int cal=Convert.ToInt32(Label1.Text)+Convert.ToInt32(Label2.Text);
        if (result.Equals(cal))
        {
            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('CORRECT CAPTCHA LOGIN SUCCESSFULL!!')", true);

        }
        else
        {

            ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "errmsg", "alert('INCORRECT TRY AGAIN')", true);

        }

    }
}


AND ITS DONE ..





Friday, 11 July 2014

HOW TO UPDATE LARGE TABLES IN FASTEST WAY....... IN SQL SERVER

FASTEST WAY TO UPDATE ROWS IN A LARGE TABLES IN SQL SERVER




The key concept here will be to improve the performance of an update operation by updating the tables in smallest manner.

For E.G:

consider a table called test with contains more than 5 millions records rows. Let us also assume what we need to update,,,say there are over 3  millions rows in that column that has a negative number so we need to update all the rows (i.e upto 3 millions) containing the negative numbers to positive numbers .


NOW normal query will be(not recommended):

update test set columnname=0 where columnanme<0;


THAT IS ROWCOUNT TO RESCUE>>>>>>>>>>>>>>>>>>>


set rowcount 10000

update test set columnname=0 where columnanme<0;

while @@rowcount>0

BEGIN
set rowcount 10000

update test set columnname=0 where columnanme<0;



//
I.E
it will updates 10000 row at a time and then loop continues till @@rowcount>0.
this will ensure that table will not locked and updation is done smoothly in less time.

DELETE DUPLICATE DATA FROM SQL SERVER CONTAINING NO PRIMARY /PRIMARY KEY.

HOW TO DELETE DUPLICATE VALUES FROM SQL TABLE


Their are severals ways this can be achieved .below are the discussed two ways:


Table structure:
username varchar2
password varchar2


--using CTE COMMON TABLE EXPRESSION and row_number function


WITH CTE AS(
   SELECT username, Password,
       RN = ROW_NUMBER()OVER(PARTITION BY username ORDER BY username)
   FROM dbo.users
)
DELETE FROM CTE WHERE RN > 1







--using auto id column


ALTER TABLE dbo.users ADD AUTOID INT IDENTITY(1,1)

select username,count(username) as counts from users group by username
having count(username)>1


delete from users where AUTOID  not in (select min(AUTOID) from users group by username)


Thus simply done..

Wednesday, 26 February 2014

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT

UPLOAD AND DOWNLOAD MULTIPLE FILES WITH SIMPLE JAVASCRIPT


DESIGN PAGE:


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

<!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 id="Head1" runat="server">
    <title></title>
    <style type="text/css">
    .fileUpload{
    width:255px;    
    font-size:11px;
    color:#000000;
    border:solid;
    border-width:1px;
    border-color:#7f9db9;    
    height:17px;
    }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="fileUploadarea"><asp:FileUpload ID="fuPuzzleImage" runat="server" CssClass="fileUpload" /><br /></div><br />
    <div><input style="display:block;" id="btnAddMoreFiles" type="button" value="Add more images" onclick="AddMoreImages();" /><br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Upload" />
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <asp:Button ID="Button2" runat="server" Text="SHOW FILES" 
            onclick="Button2_Click" />
        &nbsp;&nbsp;&nbsp;&nbsp;
        <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>

        </div>
        <div id="download" runat="server">
        
      <p>  ALL AVAILABEL FILES :<br /></p>
      <br />
        
        </div>
    </div>
    <script language="javascript" type="text/javascript">
        function AddMoreImages() {
            if (!document.getElementById && !document.createElement)
                return false;
            var fileUploadarea = document.getElementById("fileUploadarea");
            if (!fileUploadarea)
                return false;
            var newLine = document.createElement("br");
            fileUploadarea.appendChild(newLine);
            var newFile = document.createElement("input");
            newFile.type = "file";
            newFile.setAttribute("class", "fileUpload");

            if (!AddMoreImages.lastAssignedId)
                AddMoreImages.lastAssignedId = 100;
            newFile.setAttribute("id", "FileUpload" + AddMoreImages.lastAssignedId);
            newFile.setAttribute("name", "FileUpload" + AddMoreImages.lastAssignedId);
            var div = document.createElement("div");
            div.appendChild(newFile);
            div.setAttribute("id", "div" + AddMoreImages.lastAssignedId);
            fileUploadarea.appendChild(div);
            AddMoreImages.lastAssignedId++;
        }
   
    </script>
    </form>
</body>
</html>




Here we are adding asp control upload dynamically (up to max 6 optionally) on btnAddMoreFiles button click and call the java script  function AddMoreImages .

Button2 Is used to list all the files been upoaded successfully . 



CODE BEHIND PAGE:

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.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Threading;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       
       }
  protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Label1.Text = "";
            HttpFileCollection hfc = Request.Files;
            
                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string type = hpf.FileName.Split(".".ToCharArray())[1].ToString();
                    if (type == "doc" || type == "docx" || type == "DOC" || type == "DOCX")
                    {
                        if (hpf.ContentLength > 0 && hpf.ContentLength < 5242880)
                        {
                            hpf.SaveAs(Server.MapPath("~/uploads/") + System.IO.Path.GetFileName(hpf.FileName));
                            Label1.Text += "<br/>file "+ hpf.FileName+" uploaded successfully...<br/>";

                        }
                        else
                        {

                            Label1.Text += "FILE of size more than 5 mb ("+hpf.FileName+") are not allowed<br />";
                        }
                    }
                    else
                    {

                        Label1.Text += "only docs file are allowed"+hpf.FileName+" NOT UPLOADED";
      
                    
                    }
                   
                }
           
               
        }
        catch (Exception)
        {
            
            throw;
        } 
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/uploads"));
        int i = 0;
        foreach (FileInfo fi in di.GetFiles())
        {
            HyperLink HL = new HyperLink();
            HL.ID = "HyperLink" + i++;
            HL.Text = fi.Name;
            HL.NavigateUrl = "Download.aspx?file=" + fi.Name;
            download.Controls.Add(HL);
            download.Controls.Add(new LiteralControl("<br/>"));
        }
    }
    }



HERE I have made a restriction that only doc files will be uploaded and of size less than 5 mb.
it depends upon you what are the conditions.
 
On button2_Click the files been uploaded are shown in hyperlink and on clicking the hyper link the file are been downloaded.


BELOW IS THE CODE FOR DOWNLOAD FILE:


using System.IO;
using System.Threading;

public partial class Download : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string filename = Request["file"].ToString();
        fileDownload(filename, Server.MapPath("~/uploads/" + filename));
    }
    private void fileDownload(string fileName, string fileUrl)
    {
        Page.Response.Clear();
        bool success = ResponseFile(Page.Request, Page.Response, fileName, fileUrl, 1024000);
        if (!success)
            Response.Write("Downloading Error!");
        Page.Response.End();

    }
    public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed)
    {
        try
        {
            FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            BinaryReader br = new BinaryReader(myFile);
            try
            {
                _Response.AddHeader("Accept-Ranges", "bytes");
                _Response.Buffer = false;
                long fileLength = myFile.Length;
                long startBytes = 0;

                int pack = 10240; //10K bytes
                int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
                if (_Request.Headers["Range"] != null)
                {
                    _Response.StatusCode = 206;
                    string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
                    startBytes = Convert.ToInt64(range[1]);
                }
                _Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
                if (startBytes != 0)
                {
                    _Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
                }
                _Response.AddHeader("Connection", "Keep-Alive");
                _Response.ContentType = "application/octet-stream";
                _Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));

                br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
                int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;

                for (int i = 0; i < maxCount; i++)
                {
                    if (_Response.IsClientConnected)
                    {
                        _Response.BinaryWrite(br.ReadBytes(pack));
                        Thread.Sleep(sleep);
                    }
                    else
                    {
                        i = maxCount;
                    }
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                br.Close();
                myFile.Close();
            }
        }
        catch
        {
            return false;
        }
        return true;
    }








Saturday, 11 January 2014

PayPal Gateway Integration in ASP.NET

PayPal Gateway Integration in ASP.NET


Introduction

If you are developing an ASP.NET web application and you require some payment gateway integration, then here is a simplified option to integrate PayPal with your application.

Description

In this article I will explain thoroughly all the requirements and techniques for integrating PayPal in your web application.
Nowadays PayPal is the most popular payment gateway worldwide because it is totally free to integrate and PayPal does not charge anything for opening an account, you will pay PayPal when you get paid. And the amount is also lower than other payment gateways. 



THE DESIGN PAGE :

This is the test page ...you can create as per your requirement.

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

<!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>PAYPAL INTEGRATION IN ASP.NET Page</title>
</head>
<body>
    <form id="form1" runat="server">
   <div style="color: #324143; margin: 30px 0 0 60px; font-family: Arial;">
    <span style="font-size: small;">Your Name:</span>
    <asp:TextBox runat="server" ValidationGroup="save" ID="txtName" Style="margin-left: 30px; width: 200px;
        background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="txtPurpose"
        ErrorMessage="Please enter your Name" runat="server" 
        ValidationGroup="save" ForeColor="red"></asp:RequiredFieldValidator>
    <br />
    <br />
    <span style="font-size: small;">Your Email Id:</span><asp:TextBox runat="server" ValidationGroup="save"
        Style="margin-left: 20px;width: 200px; background-image: url('../images/txtBoxbg.jpg') no-repeat;"
        ID="txtEmailId"></asp:TextBox>
    <asp:RegularExpressionValidator ID="regexEmailValid" runat="server" 
        ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
        ControlToValidate="txtEmailId" ValidationGroup="save" 
        ErrorMessage="Invalid Email Format" 
        ForeColor="red"></asp:RegularExpressionValidator><br />
    <br />
    <span style="font-size: small;">Your Phone No:</span>
    <asp:TextBox runat="server" ID="txtPhone" ValidationGroup="save" Style="margin-left: 6px;
        width: 200px; background-image: transparent url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RegularExpressionValidator ID="RegularExpressionValidator4" runat="server" ControlToValidate="txtPhone"
        ForeColor="red" ErrorMessage="Invalid Phone No"
        ValidationGroup="save" ValidationExpression="^([0-9\(\)\/\+ \-]*)$"></asp:RegularExpressionValidator>
    <br />
    <br />
    <span style="font-size: small;">Enter Amount:</span><asp:TextBox runat="server" ID="txtAmount" ValidationGroup="save"
        Style="margin-left: 16px; width: 200px; background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" ControlToValidate="txtAmount"
        runat="server" ForeColor="red" ErrorMessage="Please enter the amount."></asp:RequiredFieldValidator>
    <br />
    <br />
    <span style="font-size: small;">Currency:</span>
    <asp:DropDownList runat="server" ID="ddlCurrency" Style="margin-left: 42px; 
        width: 204px; background-image: transparent url('../images/txtBoxbg.jpg') no-repeat;">
        <asp:ListItem>- Select -</asp:ListItem>
        <asp:ListItem>INR</asp:ListItem>
        <asp:ListItem>USD</asp:ListItem>
        <asp:ListItem>EURO</asp:ListItem>
        <asp:ListItem>Pound</asp:ListItem>
    </asp:DropDownList>
    <br />
    <br />
    <span style="font-size: small;">Your Purpose:</span><asp:TextBox TextMode="MultiLine" 
        Rows="10" runat="server" ID="txtPurpose"
        Height="50px" 
        Style="margin-left: 17px; margin-left: 19px; width: 200px; 
               background-image: url('../images/txtBoxbg.jpg') no-repeat;"></asp:TextBox>
    <asp:RequiredFieldValidator ID="RequiredFieldValidator6" ControlToValidate="txtPurpose"
        ErrorMessage="Can not be left blank" ValidationGroup="save" 
        runat="server" ForeColor="red"></asp:RequiredFieldValidator>
    <br />
    <asp:Button ID="btnPay" runat="server" Text="Pay Now" CssClass="button" Style="font-size: 12px;
        cursor: pointer; height: 27px; margin-left: 207px; margin-top: 10px; width: 93px;"
        OnClick="btnPay_AsPerYourChoice" ValidationGroup="save"></asp:Button>
</div>
    </form>
</body>
</html>




THE CODE BEHIND:

HERE BEFORE ADDING CODE YOU NEED TO HAVE AN AUTHORIZED ACCOUNT OR TRY WITH TESTING VERSION AS I HAVE DID::::

  //<!--Here i used sandbox site url only if you hosted in live change sandbox to live paypal URL-->
        //paypal account sandbox URL:  https://www.sandbox.paypal.com/cgi-bin/webscr
         
   // <add key="PayPalSubmitUrl" value="https://www.paypal.com/cgi-bin/webscr"/>

   // <add key="FailedURL" value="http://www.mrsoft.co.in/ProceedToPayment.aspx"/>

   // <add key="SuccessURL" value="http://www.mrsoft.co.in/ProceedToPayment.aspx"/>

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;

public partial class PaymentIntegration : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
    }
    protected void PayWithPayPal(string amount, string itemInfo, string name,
          string phone, string email, string currency)
    {
        string redirecturl = "";

        //Mention URL to redirect content to paypal site
        redirecturl += "https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=" +
                       ConfigurationManager.AppSettings["paypalemail"].ToString();

        //First name i assign static based on login details assign this value
        redirecturl += "&first_name=" + name;

        //City i assign static based on login user detail you change this value
        redirecturl += "&city=BANGALORE";

        //State i assign static based on login user detail you change this value
        redirecturl += "&state=YELHANKA NEW TOWM";

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Product Name
        redirecturl += "&amount=" + amount;

        //Phone No
        redirecturl += "&night_phone_a=" + phone;

        //Product Name
        redirecturl += "&item_name=" + itemInfo;

        //Address 
        redirecturl += "&address1=" + email;

        //Business contact id
        // redirecturl += "&business=piyushrana1991@gmail.com";

        //Shipping charges if any
        redirecturl += "&shipping=0";

        //Handling charges if any
        redirecturl += "&handling=0";

        //Tax amount if any
        redirecturl += "&tax=0";

        //Add quatity i added one only statically 
        redirecturl += "&quantity=1";

        //Currency code 
        redirecturl += "&currency=" + currency;

        //Success return page url
        redirecturl += "&return=" +
          ConfigurationManager.AppSettings["SuccessURL"].ToString();

        //Failed return page url
        redirecturl += "&cancel_return=" +
          ConfigurationManager.AppSettings["FailedURL"].ToString();

        Response.Redirect(redirecturl);


         
    }
    protected void btnPay_AsPerYourChoice(object sender, EventArgs e)
    {
        PayWithPayPal(txtAmount.Text.ToString(),txtPurpose.Text.ToString(), txtName.Text.ToString(), txtPhone.Text.ToString(), txtEmailId.Text.ToString(), ddlCurrency.SelectedItem.Text.ToString());
    }
}



      //The COMPLETE URL GENERATED AFTER EXECTION
    //   https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_xclick&business=piyushrana1991@live.com&first_name=piyush&city=BANGALORE&state=YELHANKA NEW TOWM&item_name=TESTING PURPOSE&amount=500&night_phone_a=9538774446&item_name=TESTING PURPOSE&address1=piyushrana1991@gmail.com&shipping=0&handling=0&tax=0&quantity=1&currency=INR&return=http://www.mrsoft.co.in/ProceedToPayment.aspx&cancel_return=http://www.mrsoft.co.in/ProceedToPayment.aspx
        
        // THE URL BEEN SHOWN BY PAYPAL(HTTPS)
        //https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_flow&SESSION=vvkc3WmzlBWoW6IQujCZ4L-egHt00STTbbNLkH4ZK-kf33C46xxdUCf4ZWC&dispatch=50a222a57771920b6a3d7b606239e4d529b525e0b7e69bf0224adecfb0124e9b61f737ba21b081986471f9b93cfa01e00b63629be0164db1





ADD DYNAMIC ROWS IN GRIDVIEW

ADD ROWS DYNAMICALLY IN GRIDVIEW


THE DESIGN PAGE:

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

<!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>AddDynamicRowsInGridview Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="ADD EMPLOYER DETAILS IN THE GRIDVIEW(EXAMPLE CODE)"></asp:Label>
        <asp:GridView ID="grvEmployeeDetails" runat="server" 
                ShowFooter="True" AutoGenerateColumns="False"
                CellPadding="4" ForeColor="#333333" 
                GridLines="None" OnRowDeleting="grvEmployeeDetails_RowDeleting" 
            >
    <Columns>
        <asp:BoundField DataField="RowNumber" HeaderText="SNo" />
        <asp:TemplateField HeaderText="Employee Name">
            <ItemTemplate>
                <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employee Age">
            <ItemTemplate>
                <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Employee Address">
            <ItemTemplate>
                <asp:TextBox ID="txtAddress" runat="server" 
                   Height="55px" TextMode="MultiLine"></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Gender">
            <ItemTemplate>
                <asp:RadioButtonList ID="RBLGender" 
                           runat="server" RepeatDirection="Horizontal">
                    <asp:ListItem Value="M">Male</asp:ListItem>
                    <asp:ListItem Value="F">Female</asp:ListItem>
                </asp:RadioButtonList>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="Qualification">
            <ItemTemplate>
                <asp:DropDownList ID="drpQualification" runat="server">
                    <asp:ListItem Value="G">Graduate</asp:ListItem>
                    <asp:ListItem Value="P">Post Graduate</asp:ListItem>
                </asp:DropDownList>
            </ItemTemplate>
            <FooterStyle HorizontalAlign="Right" />
            <FooterTemplate>
                <asp:Button ID="ButtonAdd" runat="server" 
                        Text="Add New Employee Details" OnClick="ButtonAdd_Click" />
            </FooterTemplate>
        </asp:TemplateField>
        <asp:CommandField ShowDeleteButton="True" />
    </Columns>
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#EFF3FB" />
    <EditRowStyle BackColor="#2461BF" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" />
</asp:GridView>
    </div>
    </form>
</body>
</html>


Here we created the gridview with custom columns .just edit as per your requirnment..
...


THE CODE BEHIND PAGE:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;


public partial class AddDynamicRowsInGridview : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FirstGridViewRow();
        
        }
    }
    private void FirstGridViewRow()
    {
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Col1", typeof(string)));
        dt.Columns.Add(new DataColumn("Col2", typeof(string)));
        dt.Columns.Add(new DataColumn("Col3", typeof(string)));
        dt.Columns.Add(new DataColumn("Col4", typeof(string)));
        dt.Columns.Add(new DataColumn("Col5", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Col1"] = string.Empty;
        dr["Col2"] = string.Empty;
        dr["Col3"] = string.Empty;
        dr["Col4"] = string.Empty;
        dr["Col5"] = string.Empty;
        dt.Rows.Add(dr);

        ViewState["CurrentTable"] = dt;

        grvEmployeeDetails.DataSource = dt;
        grvEmployeeDetails.DataBind();
    }
    private void AddNewRow()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxName =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                               TextBox TextBoxAge =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;

                    dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
                    dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
                    dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
                    dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
                    rowIndex++;
                }
                dtCurrentTable.Rows.Add(drCurrentRow);
                ViewState["CurrentTable"] = dtCurrentTable;

                grvEmployeeDetails.DataSource = dtCurrentTable;
                grvEmployeeDetails.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        SetPreviousData();
    }

    private void SetPreviousData()
    {
        int rowIndex = 0;
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    TextBox TextBoxName = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox TextBoxAge = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress =
                      (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");

                    TextBoxName.Text = dt.Rows[i]["Col1"].ToString();
                    TextBoxAge.Text = dt.Rows[i]["Col2"].ToString();
                    TextBoxAddress.Text = dt.Rows[i]["Col3"].ToString();
                    RBLGender.SelectedValue = dt.Rows[i]["Col4"].ToString();
                    DrpQualification.SelectedValue = dt.Rows[i]["Col5"].ToString();
                    rowIndex++;
                }
            }
        }
    }
    protected void grvEmployeeDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        SetRowData();
        if (ViewState["CurrentTable"] != null)
        {
            DataTable dt = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            int rowIndex = Convert.ToInt32(e.RowIndex);
            if (dt.Rows.Count > 1)
            {
                dt.Rows.Remove(dt.Rows[rowIndex]);
                drCurrentRow = dt.NewRow();
                ViewState["CurrentTable"] = dt;
                grvEmployeeDetails.DataSource = dt;
                grvEmployeeDetails.DataBind();

                for (int i = 0; i < grvEmployeeDetails.Rows.Count - 1; i++)
                {
                    grvEmployeeDetails.Rows[i].Cells[0].Text = Convert.ToString(i + 1);
                }
                SetPreviousData();
            }
        }
    }
    private void SetRowData()
    {
        int rowIndex = 0;

        if (ViewState["CurrentTable"] != null)
        {
            DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
            DataRow drCurrentRow = null;
            if (dtCurrentTable.Rows.Count > 0)
            {
                for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
                {
                    TextBox TextBoxName = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[1].FindControl("txtName");
                    TextBox TextBoxAge = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[2].FindControl("txtAge");
                    TextBox TextBoxAddress = (TextBox)grvEmployeeDetails.Rows[rowIndex].Cells[3].FindControl("txtAddress");
                    RadioButtonList RBLGender =
                      (RadioButtonList)grvEmployeeDetails.Rows[rowIndex].Cells[4].FindControl("RBLGender");
                    DropDownList DrpQualification =
                      (DropDownList)grvEmployeeDetails.Rows[rowIndex].Cells[5].FindControl("drpQualification");
                    drCurrentRow = dtCurrentTable.NewRow();
                    drCurrentRow["RowNumber"] = i + 1;
                    dtCurrentTable.Rows[i - 1]["Col1"] = TextBoxName.Text;
                    dtCurrentTable.Rows[i - 1]["Col2"] = TextBoxAge.Text;
                    dtCurrentTable.Rows[i - 1]["Col3"] = TextBoxAddress.Text;
                    dtCurrentTable.Rows[i - 1]["Col4"] = RBLGender.SelectedValue;
                    dtCurrentTable.Rows[i - 1]["Col5"] = DrpQualification.SelectedValue;
                    rowIndex++;
                }

                ViewState["CurrentTable"] = dtCurrentTable;
                //grvStudentDetails.DataSource = dtCurrentTable;
                //grvStudentDetails.DataBind();
            }
        }
        else
        {
            Response.Write("ViewState is null");
        }
        //SetPreviousData();
    }
    protected void ButtonAdd_Click(object sender, EventArgs e)
    {

        AddNewRow();
    }
}


Here we created four function to add new row...AddNewRow() and set previous data in gridview.