Wednesday, October 31, 2012

Asp.Net Call WebService With Parameters From JavaScript JQuery

This example covers how to Call Asp.Net WebService PageMethods Or WebMethod With Parameters From JQuery Or JavaScript.

To Call WebService PageMethod through Ajax ,JavaScript or JQuery we need to uncomment or add following line before writing WebMethod


[System.Web.Script.Services.ScriptService]

Add jquery-1.7.2.min.js in application and reference it in Head section of page.

<head runat="server">
<script src="jquery-1.7.2.min.js" type="text/javascript"/>  
</head>

Add and create Web Service by Right click on solution explorer > Add New Item > WebService.asmx.
I have created a WebMethod which takes and return string parameter in it.

Call Asp.Net WebService From JQuery Or JavaScript


C# CODE

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string Welcome(string name) 
    { 
        return "Welcome " + name;
    }
}

VB.NET CODE
 
 Public Function Welcome(name As String) As String
  Return "Welcome " & name
 End Function
End Class

Place one text input html control, one input button type on page, you can place asp.net button control either.
Enter Name: <input type="text" id="txtName" />
<asp:Button ID="btn" runat="server" Text="Invoke WebService" 
            OnClientClick="CallWebService(); return false;"/>
        
<asp:Label ID="lblMsg" runat="server" Text=""/>
 
<input type="button" id="btnCall" value="Call Service" 
       onclick="CallWebService(); return false;"/>

Add following Script in Head section of page to call PageMethod using JQuery.

To call WebService using JavaScript, we can write script as follows
Place ScriptManager on the page and add ServiceReference and path in it.

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>

Write this Script in Head of page.

Build and run the code.

Print GridView Data In Asp.Net Using C# VB JavaScript

To Print GridView Data In Asp.Net Using C# And VB.NET, I have placed GridView inside a Div and this Div will be called for printing using javascript.

Print window will be opened in onclick event of Button. Javascript to print data is written in Page Load event of page and registered with RegisterStartupScript.


Print GridView Data In Asp.Net C# VB

HTML SOURCE OF GRIDVIEW
   1:  <div id="gvDiv">
   2:   
   3:  <asp:GridView ID="gvPrint" runat="server" 
   4:                DataSourceID="SqlDataSource1">
   5:  <Columns>
   6:  <asp:BoundField DataField="CategoryID" 
   7:                  HeaderText="CategoryID"/>
   8:  <asp:BoundField DataField="CategoryName" 
   9:                  HeaderText="CategoryName"/>
  10:  </Columns>
  11:  </asp:GridView>
  12:  </div>
  13:     
  14:  <asp:Button ID="btnPrint" runat="server" 
  15:              Text="Print Data"/>

C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        string printScript =
        @"function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gvDiv');
            var printWindow = window.open('gview.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}";
        this.ClientScript.RegisterStartupScript(Page.GetType(), "PrintGridView", printScript.ToString(), true);
        btnPrint.Attributes.Add("onclick", "PrintGridView();");       
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim printScript As String = "function PrintGridView()
         {
            var gridInsideDiv = document.getElementById('gvDiv');
            var printWindow = window.open('gv.htm','PrintWindow','letf=0,top=0,width=150,height=300,toolbar=1,scrollbars=1,status=1');
            printWindow.document.write(gridInsideDiv.innerHTML);
            printWindow.document.close();
            printWindow.focus();
            printWindow.print();
            printWindow.close();}"
 Me.ClientScript.RegisterStartupScript(Page.[GetType](), "PrintGridView", printScript.ToString(), True)
 btnPrint.Attributes.Add("onclick", "PrintGridView();")
End Sub

Nested GridView Example In Asp.Net With Expand Collapse

This example shows how to create Nested GridView In Asp.Net Using C# And VB.NET With Expand Collapse Functionality.
I have used JavaScript to Create Expandable Collapsible Effect by displaying Plus Minus image buttons.


Nested GridView Example In Asp.Net With Expand Collapse

Customers and Orders Table of Northwind Database are used to populate nested GridViews.

Drag and place SqlDataSource from toolbox on aspx page and configure and choose it as datasource from smart tags

Go to HTML source of page and add 2 TemplateField in <Columns>, one as first column and one as last column of gridview.

Place another grid in last templateField column.

Markup of page after adding both templatefields will like as shown below.



HTML SOURCE
   1:  <asp:GridView ID="gvMaster" runat="server" 
   2:                AllowPaging="True" 
   3:                AutoGenerateColumns="False" 
   4:                DataKeyNames="CustomerID" 
   5:                DataSourceID="SqlDataSource1" 
   6:                onrowdatabound="gvMaster_RowDataBound">
   7:  <Columns>
   8:  <asp:TemplateField>
   9:      <ItemTemplate>
  10:      <a href="javascript:collapseExpand('customerID-
  11:               <%# Eval("CustomerID") %>');">
  12:      <img id="imagecustomerID-<%# Eval("CustomerID") %>" 
  13:           alt="Click to show/hide orders" 
  14:           border="0" src="plus.png" /></a>
  15:      </ItemTemplate>
  16:  </asp:TemplateField>
  17:  <asp:BoundField DataField="CustomerID" 
  18:                  HeaderText="CustomerID"/>
  19:  <asp:BoundField DataField="CompanyName" 
  20:                  HeaderText="CompanyName"/>
  21:   
  22:  <asp:TemplateField>
  23:  <ItemTemplate>
  24:  <tr><td colspan="100%">
  25:  <div id="customerID-<%# Eval("CustomerID") %>" 
  26:       style="display:none;
  27:       position:relative;left:25px;">
  28:       
  29:  <asp:GridView ID="nestedGridView" runat="server" 
  30:                AutoGenerateColumns="False" 
  31:                DataKeyNames="OrderID">
  32:  <Columns>
  33:  <asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
  34:  <asp:BoundField DataField="OrderDate" HeaderText="OrderDate"/>
  35:  <asp:BoundField DataField="Freight" HeaderText="Freight"/>
  36:  </Columns>
  37:  </asp:GridView>
  38:  </div>
  39:  </td></tr>
  40:  </ItemTemplate>
  41:  </asp:TemplateField>
  42:  </Columns>
  43:  </asp:GridView>
  44:   
  45:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  46:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>" 
  47:  SelectCommand="SELECT [CustomerID], [CompanyName] 
  48:                 FROM [Customers]">
  49:  </asp:SqlDataSource>

Add following JavaScript in head section of page.

Write following code in RowDataBound Event of parent Grid to populate nested gridview.

C#
protected void gvMaster_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string customerID = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CustomerID"));
            GridView gvChild = (GridView)e.Row.FindControl("nestedGridView");
            SqlDataSource gvChildSource = new SqlDataSource();
            gvChildSource.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            gvChildSource.SelectCommand = "SELECT [OrderID], [OrderDate],[Freight] FROM [Orders] WHERE [CustomerID] = '" + customerID + "'";
            gvChild.DataSource = gvChildSource;
            gvChild.DataBind();
        }
    }

VB.NET
Protected Sub gvMaster_RowDataBound(sender As Object, e As GridViewRowEventArgs)
 If e.Row.RowType = DataControlRowType.DataRow Then
  Dim customerID As String = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "CustomerID"))
  Dim gvChild As GridView = DirectCast(e.Row.FindControl("nestedGridView"), GridView)
  Dim gvChildSource As New SqlDataSource()
  gvChildSource.ConnectionString = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
  gvChildSource.SelectCommand = "SELECT [OrderID], [OrderDate],[Freight] FROM [Orders] WHERE [CustomerID] = '" + customerID + "'"
  gvChild.DataSource = gvChildSource
  gvChild.DataBind()
 End If
End Sub

Build and run the application to test GridView Inside Grid.

Download Sample Code

Display Files In GridView From Server Directory Asp.Net

This Example Show How To Display Files Directory Sub Directories In GridView From Server Folder In Asp.Net application using C# and Vb.Net.

We need to use DirectoryInfo class under System.IO namespace.

I'm displaying all files and directories (folders) from sever in gridview in page load.

I m creating a datatable in code behind with Name, Size and Type columns and assigning it as DataSource to Gridview.

Data in DataTable rows is coming from looping through all file and folder information stored in FileInfo or DirectoryInfo Arrays of GetFiles and GetDirectories methods of DirectoryInfo Class Object,

GetFiles method returns all the files and GetDirectories method returns all the directories or folder in server path specified.

Display Files Folders Directories In GridView From Server Folder Asp.Net

To search all files i'm passing *.* and SearchOption.AllDirectories parameters in GetDirectories method,

we can display specific file type in gridview by specifying it's extension instead of *.* (for example *.jpg or filename.*). SearchOption.AllDirectories parameter search files in all sub directories

C# CODE


protected void Page_Load(object sender, EventArgs e)
    {
        DataTable gvSource = DisplayFilesInGridView();
        DataRow gvRow;

        //Get All Folders Or Directories and add in table
        DirectoryInfo directory = new DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"));
        DirectoryInfo[] subDirectories = directory.GetDirectories();
        foreach (DirectoryInfo dirInfo in subDirectories)
        {
            gvRow = gvSource.NewRow();
            gvRow["Name"] = dirInfo.Name;
            gvRow["Type"] = "Directory";
            gvSource.Rows.Add(gvRow);
        }
        //Get files in all directories 
        FileInfo[] files = directory.GetFiles("*.*", SearchOption.AllDirectories);
        foreach (FileInfo fileInfo in files)
        {
            gvRow = gvSource.NewRow();
            gvRow["Name"] = fileInfo.Name;
            gvRow["Size"] = fileInfo.Length;
            gvRow["Type"] = "File";
            gvSource.Rows.Add(gvRow);
 
        }
        gridviewDisplayFilesDirectories.DataSource = gvSource;
        gridviewDisplayFilesDirectories.DataBind();
    }

    private DataTable DisplayFilesInGridView()
    {
        DataTable dtGvSource = new DataTable();
        dtGvSource.Columns.Add(new DataColumn("Name", typeof(System.String)));
        dtGvSource.Columns.Add(new DataColumn("Size", typeof(System.String)));
        dtGvSource.Columns.Add(new DataColumn("Type", typeof(System.String)));
        return dtGvSource;
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 Dim gvSource As DataTable = DisplayFilesInGridView()
 Dim gvRow As DataRow

 'Get All Folders Or Directories and add in table
 Dim directory As New DirectoryInfo(Server.MapPath("~/csharpdotnetfreak.blogspot.com"))
 Dim subDirectories As DirectoryInfo() = directory.GetDirectories()
 For Each dirInfo As DirectoryInfo In subDirectories
  gvRow = gvSource.NewRow()
  gvRow("Name") = dirInfo.Name
  gvRow("Type") = "Directory"
  gvSource.Rows.Add(gvRow)
 Next
 'Get files in all directories 
 Dim files As FileInfo() = directory.GetFiles("*.*", SearchOption.AllDirectories)
 For Each fileInfo As FileInfo In files
  gvRow = gvSource.NewRow()
  gvRow("Name") = fileInfo.Name
  gvRow("Size") = fileInfo.Length
  gvRow("Type") = "File"

  gvSource.Rows.Add(gvRow)
 Next
 gridviewDisplayFilesDirectories.DataSource = gvSource
 gridviewDisplayFilesDirectories.DataBind()
End Sub

Private Function DisplayFilesInGridView() As DataTable
 Dim dtGvSource As New DataTable()
 dtGvSource.Columns.Add(New DataColumn("Name", GetType(System.String)))
 dtGvSource.Columns.Add(New DataColumn("Size", GetType(System.String)))
 dtGvSource.Columns.Add(New DataColumn("Type", GetType(System.String)))
 Return dtGvSource
End Function


Download Sample Code

Drag Drop GridView Rows With JQuery Asp.Net

This Example explains How To Implement Drag And Drop GridView Rows Functionality Using JQuery JavaScript In Asp.Net 2.0 3.5 4.0 To Rearrange Row On Client Side.

You need to download and add JQuery and TableDnD plugin in your application.

GridView is populated with Northwind database using SqlDataSource.


Drag Drop Gridview Rows Using JQuery


Add Script references and css style in head section of page.

   1:  <style type="text/css">
   2:     .highlight
   3:      {
   4:          color : White !important;
   5:          background-color : Teal !important;
   6:      }
   7:  </style>
   8:  <script src="jquery-1.7.1.js" type="text/javascript"/>
   9:  <script src="jquery.tablednd.0.7.min.js" type="text/javascript"/>

Call tableDnD function of drag and drop plugin by passing Gridview Id.

   1:  <script type="text/javascript" language="javascript">
   2:  $(document).ready(function() 
   3:  {
   4:  $("#<%=GridView1.ClientID%>").tableDnD(
   5:              {
   6:                  onDragClass: "highlight"
   7:              });
   8:  });
   9:  </script>
  10:  </head>

   1:  <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
   2:                AutoGenerateColumns="False" DataKeyNames="OrderID" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="OrderID" HeaderText="OrderID"/>
   6:  <asp:BoundField DataField="Freight" HeaderText="Freight"/>
   7:  <asp:BoundField DataField="ShipName" HeaderText="ShipName"/>
   8:  <asp:BoundField DataField="ShipCity" HeaderText="ShipCity"/>
   9:  <asp:BoundField DataField="ShipCountry" HeaderText="ShipCountry"/>
  10:  </Columns>
  11:  </asp:GridView>

Build and run the code.

Insert Update Edit Delete Rows Record In GridView

In this example i am explaining how to Insert Update Edit Delete Records Rows In GridView With SqlDataSource Using C# VB.NET Asp.Net using SqlDataSource.

For inserting record, i've put textboxes in footer row of GridView using ItemTemplate and FooterTemaplete.


Go to design view of aspx page and drag a GridView control from toolbox, click on smart tag of GridView and choose new datasource
Select Database and click Ok
 
In next screen, Enter your SqlServer name , username and password and pick Database name from the dropdown , Test the connection
 
 
 In next screen, select the table name and fields , Click on Advance tab and check Generate Insert,Edit and Delete statements checkbox , alternatively you can specify your custom sql statements 
 
 
Click on ok to finish 
Check Enable Editing , enable deleting checkbox in gridView smart tag 
Now go to html source of page and define DatakeyNames field in gridview source
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
</asp:GridView>
Remove the boundFields and put ItemTemplate and EditItemTemplate and labels and textboxs respectively, complete html source of page should look like this
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" 
              DataKeyNames="ID"
              DataSourceID="SqlDataSource1" 
              OnRowDeleted="GridView1_RowDeleted" 
              OnRowUpdated="GridView1_RowUpdated" 
              ShowFooter="true" 
              OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:CommandField ShowDeleteButton="True" 
                      ShowEditButton="True" />
    <asp:TemplateField HeaderText="ID" SortExpression="ID">
    <ItemTemplate>
    <asp:Label ID="lblID" runat="server" 
                          Text='<%#Eval("ID") %>'>
    </asp:Label>
    </ItemTemplate>
    <FooterTemplate>
    <asp:Button ID="btnInsert" runat="server" 
                Text="Insert" CommandName="Add" />
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="FirstName" 
                       SortExpression="FirstName">
    <ItemTemplate>
    <asp:Label ID="lblFirstName" runat="server" 
               Text='<%#Eval("FirstName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtFirstName" runat="server" 
                 Text='<%#Bind("FirstName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtFname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="LastName" 
                       SortExpression="LastName">
    <ItemTemplate>
    <asp:Label ID="lblLastName" runat="server" 
               Text='<%#Eval("LastName") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLastName" runat="server" 
                 Text='<%#Bind("LastName") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLname" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Department" 
                       SortExpression="Department">
    <ItemTemplate>
    <asp:Label ID="lblDepartment" runat="server" 
               Text='<%#Eval("Department") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtDepartmentName" runat="server" 
                 Text='<%#Bind("Department") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtDept" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
    
    <asp:TemplateField HeaderText="Location" 
                       SortExpression="Location">
    <ItemTemplate>
    <asp:Label ID="lblLocation" runat="server" 
               Text='<%#Eval("Location") %>'>
    </asp:Label>
    </ItemTemplate>
    <EditItemTemplate>
    <asp:TextBox ID="txtLocation" runat="server" 
                 Text='<%#Bind("Location") %>'>
    </asp:TextBox>
    </EditItemTemplate>
    <FooterTemplate>
    <asp:TextBox ID="txtLoc" runat="server">
    </asp:TextBox>
    </FooterTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:DBConString%>"
DeleteCommand="DELETE FROM [Employees] WHERE [ID] = @ID" 
InsertCommand="INSERT INTO [Employees] ([FirstName], 
[LastName],[Department], [Location]) 
VALUES (@FirstName, @LastName, @Department, @Location)"
SelectCommand="SELECT [ID], [FirstName], [LastName], 
[Department], [Location] FROM [Employees]"
UpdateCommand="UPDATE [Employees] SET 
[FirstName] = @FirstName, [LastName] = @LastName, 
[Department] = @Department, [Location] = @Location 
WHERE [ID] = @ID" OnInserted="SqlDataSource1_Inserted">

<DeleteParameters>
    <asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
    <asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
    <asp:Parameter Name="FirstName" Type="String" />
    <asp:Parameter Name="LastName" Type="String" />
    <asp:Parameter Name="Department" Type="String" />
    <asp:Parameter Name="Location" Type="String" />
</InsertParameters>
</asp:SqlDataSource>
<asp:Label ID="lblMessage" runat="server" 
           Font-Bold="True"></asp:Label><br />
</div>
</form>
Write this code in RowCommand Event of GridView in codebehind
C# code Behind
protected void GridView1_RowCommand
(object sender, GridViewCommandEventArgs e)
{
  if (e.CommandName == "Add")
  {
   string strFirstName = ((TextBox)
   GridView1.FooterRow.FindControl("txtFname")).Text;

   string strLastName = 
   ((TextBox)GridView1.FooterRow.FindControl
                         ("txtLname")).Text;

   string strDepartment = 
   ((TextBox)GridView1.FooterRow.FindControl
                            ("txtDept")).Text;
   string strLocation = ((TextBox)GridView1.FooterRow.
                          FindControl("txtLoc")).Text;
   //SqlDataSource1.InsertParameters.Clear();
   //SqlDataSource1.InsertParameters.Add
                       //("FirstName", strFirstName);
   //SqlDataSource1.InsertParameters.Add
                          //("LastName", strLastName);
   //SqlDataSource1.InsertParameters.Add
                         //("Department", strDepartment);
   //SqlDataSource1.InsertParameters.Add
                              //("Location", strLocation);

  SqlDataSource1.InsertParameters["FirstName"].DefaultValue 
                                             = strFirstName;
  SqlDataSource1.InsertParameters["LastName"].DefaultValue 
                                             = strLastName;
  SqlDataSource1.InsertParameters["Department"].DefaultValue 
                                             = strDepartment;
  SqlDataSource1.InsertParameters["Location"].DefaultValue
                                            = strLocation;
  SqlDataSource1.Insert();
  }
}

VB.NET Code Behind
Protected Sub GridView1_RowCommand(ByVal sender As Object, 
                       ByVal e As GridViewCommandEventArgs)
        If e.CommandName = "Add" Then
            Dim strFirstName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtFname"), TextBox).Text()

            Dim strLastName As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLname"), TextBox).Text()

            Dim strDepartment As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtDept"), TextBox).Text()
            Dim strLocation As String = 
            DirectCast(GridView1.FooterRow.
            FindControl("txtLoc"), TextBox).Text()

            'SqlDataSource1.InsertParameters.Clear();
            'SqlDataSource1.InsertParameters.Add
            '("FirstName", strFirstName);
            'SqlDataSource1.InsertParameters.Add
            '("LastName", strLastName);
            'SqlDataSource1.InsertParameters.Add
            '("Department", strDepartment);
            'SqlDataSource1.InsertParameters.Add
            '("Location", strLocation);

            SqlDataSource1.InsertParameters("FirstName").
            DefaultValue = strFirstName
            SqlDataSource1.InsertParameters("LastName").
            DefaultValue = strLastName
            SqlDataSource1.InsertParameters("Department").
            DefaultValue = strDepartment
            SqlDataSource1.InsertParameters("Location").
            DefaultValue = strLocation
            SqlDataSource1.Insert()
        End If
    End Sub


Download the sample code attached


You would also like to read
Edit or update multiple records/rows in gridview with checkbox using C# in ASP.NET

Delete multiple rows records in Gridview with checkbox and confirmation in ASP.NET

Cross Page Posting PostBack In ASP.NET

In this example i am showing how to use Cross Page Posting or Postback In ASP.NET 2.0, 3.5, 4.0 Using C# And VB.NET. Cross Page posting is used to submit a form on one page (say default.aspx) and retrieve values of controls of this page on another page (say Default2.aspx)

There are two ways we can use cross page postsbacks in ASP.NET

1st method
In this i've created a Default.aspx page with two textbox and one button , button click will post back to Default2.aspx and there we will retrieve and show values of both textboxes

Html source of Default.aspx page is like

<%@ 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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:TextBox ID="txtFirstName" runat="server">
</asp:TextBox><br /><br />
Last Name:
<asp:TextBox ID="txtLastName" runat="server">
</asp:TextBox><br /><br /><br />
        
<asp:Button ID="btnSubmit" runat="server" 
            OnClick="btnSubmit_Click" 
            PostBackUrl="~/Default2.aspx"
            Text="Submit to Second Page" /><br />
</div>
</form>
</body>
</html>
Don't forget to set PostBackUrl Property of Button
PostBackUrl="~/Default2.aspx"

Now to retrieve values of textBoxes on Default2.aspx page, write below mentioned code in Page_Load event of second page (Default2.aspx)
C# code behind
protected void Page_Load(object sender, EventArgs e)
{
    //Check whether previous page is cross page post back or not
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        TextBox txtPbFirstName = (TextBox)PreviousPage.FindControl("txtFirstName");
        TextBox txtPbLastName = (TextBox)PreviousPage.FindControl("txtLastName");
        Label1.Text = "Welcome " + txtPbFirstName.Text + " " + txtPbLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}
VB.NET Code behind
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    'Check whether previous page is cross page post back or not
    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
        Dim txtPbFirstName As TextBox = DirectCast(PreviousPage.FindControl("txtFirstName"), TextBox)
        Dim txtPbLastName As TextBox = DirectCast(PreviousPage.FindControl("txtLastName"), TextBox)
        Label1.Text = ("Welcome " & txtPbFirstName.Text & " ") + txtPbLastName.Text
    Else
        Response.Redirect("Default.aspx")
    End If
End Sub

If you are using masterpages then you need to write code to FindControl as mentioned below
ContentPlaceHolder exampleHolder =(ContentPlaceHolder)Page.PreviousPage.Form.FindControl ("Content1"));
TextBox txtExample = exampleHolder.FindControl("txtFirstName");

2nd Method
Using Property to expose and Consume values of TextBox
If we are using this method then we don't need to use FindControl method at all
For this we need to create property in code behind of the page to be cross page post back (Default.aspx)
Html of the page needs no changes ,
C# code behind for Default.aspx
public TextBox pbTxtFirstName
    {
        get
        {
            return txtFirstName;
        }
    }

    public TextBox pbTxtLastName
    {
        get
        {
            return txtLastName;
        }
    }

VB.NET
Public ReadOnly Property pbTxtFirstName() As TextBox
    Get
        Return txtFirstName
    End Get
End Property

Public ReadOnly Property pbTxtLastName() As TextBox
    Get
        Return txtLastName
    End Get
End Property
Now to retrieve or consume exposed properties on Second page we need to add below mentioned page directive in html source of Default2.aspx page(usually at the top of page)
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
Now write this code in page_Load event of second page to retrieve values of controls
C# code
protected void Page_Load(object sender, EventArgs e)
{
    if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
    {
        Label1.Text = "Welcome " + PreviousPage.pbTxtFirstName.Text + " " + PreviousPage.pbTxtLastName.Text;
    }
    else
    {
        Response.Redirect("Default.aspx");
    }
}
VB Code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If PreviousPage IsNot Nothing AndAlso PreviousPage.IsCrossPagePostBack Then
        Label1.Text = ("Welcome " & PreviousPage.pbTxtFirstName.Text & " ") + PreviousPage.pbTxtLastName.Text
    Else
        Response.Redirect("Default.aspx")
        
    End If
End Sub

Hope this helps

Check All Checkbox In GridView To Bulk Edit Update ASP.NET

This example explains how to use Check All Checkbox In GridView To Bulk Edit Or Update in ASP.NET with C# and VB.NET. I have put a checkBox in header Template of gridview which on checking will check all rows in gridview using server side code to implement CheckAll CheckBox functionality.


CheckAll CheckBox In GridView to Edit and Update


Html SOURCE OF GRIDVIEW
<asp:GridView ID="GridView1" runat="server" 
              DataSourceID="SqlDataSource1" 
              AutoGenerateColumns="false" 
              CellPadding="2" ForeColor="#333333" 
              GridLines="Both" 
              DataKeyNames="ID" 
              OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelectAll_CheckedChanged"/>
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" 
              AutoPostBack="true" 
              OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate>
</asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID" 
                SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate>
<asp:TextBox ID="txtName" runat="server" 
             Text='<%# Bind("Name") %>' ForeColor="Blue" 
             BorderStyle="none" BorderWidth="0px" 
             ReadOnly="true" >
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server" 
             Text='<%# Bind("Location") %>' 
             ForeColor="Blue" BorderStyle="none" 
             ReadOnly="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" 
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" 
UpdateCommand="UPDATE [Details] SET [Name] = @Name, 
               [Location] = @Location WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>

<UpdateParameters>
<asp:Parameter Name="Name" />
<asp:Parameter Name="Location" />
<asp:Parameter Name="ID" />
</UpdateParameters>
</asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server" 
            OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server" 
            OnClick="btnDelete_Click" 
            Text="Delete" />

C# CODE
protected void chkSelectAll_CheckedChanged
                               (object sender, EventArgs e)
{
 CheckBox chkAll = 
    (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
 if (chkAll.Checked == true)
 {
   foreach (GridViewRow gvRow in GridView1.Rows)
   {
    CheckBox chkSel = 
         (CheckBox)gvRow.FindControl("chkSelect");
    chkSel.Checked = true;
    TextBox txtname = (TextBox)gvRow.FindControl("txtName");
    TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
    txtname.ReadOnly = false;
    txtlocation.ReadOnly = false;
    txtname.ForeColor = System.Drawing.Color.Black;
    txtlocation.ForeColor = System.Drawing.Color.Black;
   }
 }
 else
 {
  foreach (GridViewRow gvRow in GridView1.Rows)
  {
   CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
   chkSel.Checked = false;
   TextBox txtname = (TextBox)gvRow.FindControl("txtName");
   TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
   txtname.ReadOnly = true;
   txtlocation.ReadOnly = true;
   txtname.ForeColor = System.Drawing.Color.Blue;
   txtlocation.ForeColor = System.Drawing.Color.Blue;
   }
  }
}

VB.NET
Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
    Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox)
    If chkAll.Checked = True Then
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = True
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = False
            txtlocation.[ReadOnly] = False
            txtname.ForeColor = System.Drawing.Color.Black
            txtlocation.ForeColor = System.Drawing.Color.Black
        Next
    Else
        For Each gvRow As GridViewRow In GridView1.Rows
            Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
            chkSel.Checked = False
            Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
            Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
            txtname.[ReadOnly] = True
            txtlocation.[ReadOnly] = True
            txtname.ForeColor = System.Drawing.Color.Blue
            txtlocation.ForeColor = System.Drawing.Color.Blue
        Next
    End If
End Sub



Hope this helps.

Merge GridView Cells Or Columns In Row ASP.NET C# VB.NET

In this example i am going to describe how to Merge GridView Cells Or Columns In Gridview Rows Using C# and VB.NET in ASP.NET Containing Same Data or content. For this i m using DataBound Event of gridview, counting total rows and then checking each cells value against value of same cell in previous row and then setting the RowSpan of cells.


Merge GridView Cells Or Columns

For this i have created a table containing Counties ,states and respective cities and country and state cells / columns are merged in rows having same country or states.


For knowing how to merge Gridview headers read article below
Merging GridView Header Columns or multiple Headers


You would also like to read
Hide GridView Columns In Normal Mode and Visible In Edit


Running Total In Gridview Footer in ASP.NET C# VB.NET











Html source of the page look like this
<asp:GridView ID="GridView1" runat="server" 
    AutoGenerateColumns="False"  
    BorderStyle="None" BorderWidth="1px" CellPadding="4" 
    GridLines="Horizontal" ForeColor="Black" 
    Height="119px" DataSourceID="SqlDataSource1" 
    OnDataBound="GridView1_DataBound1"> 
            <Columns>
            <asp:BoundField DataField="Country" 
                            HeaderText="Country" 
                            SortExpression="Country" />
            <asp:BoundField DataField="State" 
                            HeaderText="State" 
                            SortExpression="State" />
            <asp:BoundField DataField="City" 
                            HeaderText="City" 
                            SortExpression="City" />
        </Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Country], [State], [City] 
               FROM [Details] ORDER BY [State]">
</asp:SqlDataSource>

C# code behind
protected void GridView1_DataBound1(object sender, EventArgs e)
{
  for (int rowIndex = GridView1.Rows.Count - 2; 
                                     rowIndex >= 0; rowIndex--)
  {
    GridViewRow gvRow = GridView1.Rows[rowIndex];
    GridViewRow gvPreviousRow = GridView1.Rows[rowIndex + 1];
    for (int cellCount = 0; cellCount < gvRow.Cells.Count; 
                                                  cellCount++)
    {
     if (gvRow.Cells[cellCount].Text == 
                            gvPreviousRow.Cells[cellCount].Text)
     {
       if (gvPreviousRow.Cells[cellCount].RowSpan < 2)
       {
         gvRow.Cells[cellCount].RowSpan = 2;
       }
       else
       {
        gvRow.Cells[cellCount].RowSpan = 
            gvPreviousRow.Cells[cellCount].RowSpan + 1;
       }
       gvPreviousRow.Cells[cellCount].Visible = false;
    }
   }
 }
}
VB.NET code behind
Protected Sub GridView1_DataBound1
           (ByVal sender As Object, ByVal e As EventArgs)

For rowIndex As Integer = GridView1.Rows.Count - 2 To 0 Step -1
    Dim gvRow As GridViewRow = GridView1.Rows(rowIndex)
    Dim gvPreviousRow As GridViewRow = GridView1.Rows(rowIndex + 1)
    For cellCount As Integer = 0 To gvRow.Cells.Count - 1
    If gvRow.Cells(cellCount).Text = 
                         gvPreviousRow.Cells(cellCount).Text Then
    If gvPreviousRow.Cells(cellCount).RowSpan < 2 Then
    gvRow.Cells(cellCount).RowSpan = 2
    Else
    gvRow.Cells(cellCount).RowSpan = 
                       gvPreviousRow.Cells(cellCount).RowSpan + 1
    End If
    gvPreviousRow.Cells(cellCount).Visible = False
    End If
    Next
  Next
End Sub

Find IP Address In ASP.NET Behind Proxy

Find IP Address Behind Proxy Or Client Machine In ASP.NET, If you want to find the IP address of visitors to your aspx page or application or wanna retrieve IP for other users than u need to write this code

Using this code we can find IP address of visitor even if visitor is behind any proxy


public string IpAddress()
{
string strIpAddress;
strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (strIpAddress == null)
{
strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
}
return strIpAddress;
}

To find IP address of a machine behind LAN you can use this code
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses
(strHostName).GetValue(1).ToString();

Export GridView To Pdf-ASP.NET

In this example i'm explaining how to Export GridView To PDF Using iTextsharp In Asp.Net 2.0,3.5,4.0 Using C# VB.NET i am exporting Gridview populated with SqlDataSource to Pdf using iTextSharp in click event of Button

I have populated gridview with SqlDataSource and placed one button on the page to create pdf from gridview.





   1:  <asp:GridView ID="GridView1" runat="server" 
   2:                AutoGenerateColumns="False" 
   3:                DataSourceID="SqlDataSource1">
   4:  <Columns>
   5:  <asp:BoundField DataField="Name" HeaderText="Name"/>
   6:  <asp:BoundField DataField="Location" HeaderText="Location"/>
   7:  </Columns>
   8:  </asp:GridView>
   9:   
  10:  <asp:Button ID="btnExport" runat="server" 
  11:              OnClick="btnExport_Click" Text="Export to PDF" />
  12:              
  13:  <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
  14:  ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
  15:  SelectCommand="SELECT [Name], [Location] FROM [Test]">
  16:  </asp:SqlDataSource>

To use iTextSharp , we need to add these namspaces in the code behind and itextsharp.dll in Bin folder of Application
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

Now in Click event of button i m creating a new HtmlForm and adding the gridview control to this form in code behind , than creating instance of StringWriter class and HtmlTextWriter to write strings and than rendernig these to form created earlier
protected void btnExport_Click
(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();

In next lines of code i m creating a new Document in specified location and opening it for writing
Document Doc = new Document();

If u wanna save the pdf in application's root folder in server
than use Requesr.PhysicalApplicationPath

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

And if u wanna save the PDF at users Desktop than use
Environment.GetFolderPath(Environment.SpecialFolder.Desktop

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Now i m adding a paragraph to this document to be used as
Header by creating a new chuck and adding it to paragraph

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

Now i m reading the html string created above through 
xmlTextReader and htmlParser to parse html elements

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


The complete code looks like this

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using System.IO;
using System.Collections;
using System.Net;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void btnExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
form.Controls.Add(GridView1);
StringWriter sw = new StringWriter();
HtmlTextWriter hTextWriter = new HtmlTextWriter(sw);
form.Controls[0].RenderControl(hTextWriter);
string html = sw.ToString();
Document Doc = new Document();

//PdfWriter.GetInstance
//(Doc, new FileStream(Request.PhysicalApplicationPath 
//+ "\\AmitJain.pdf", FileMode.Create));

PdfWriter.GetInstance
(Doc, new FileStream(Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf", FileMode.Create));
Doc.Open();

Chunk c = new Chunk
("Export GridView to PDF Using iTextSharp \n",
FontFactory.GetFont("Verdana", 15));
Paragraph p = new Paragraph();
p.Alignment = Element.ALIGN_CENTER;
p.Add(c);
Chunk chunk1 = new Chunk
("By Amit Jain, amit_jain_online@yahoo.com \n",
FontFactory.GetFont("Verdana", 8));
Paragraph p1 = new Paragraph();
p1.Alignment = Element.ALIGN_RIGHT;
p1.Add(chunk1);

Doc.Add(p);
Doc.Add(p1);

System.Xml.XmlTextReader xmlReader =
new System.Xml.XmlTextReader(new StringReader(html));
HtmlParser.Parse(Doc, xmlReader);

Doc.Close();
string Path = Environment.GetFolderPath
(Environment.SpecialFolder.Desktop)
+ "\\AmitJain.pdf";


ShowPdf(Path);


}

private void ShowPdf(string strS)
{
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.AddHeader
("Content-Disposition","attachment; filename=" + strS);
Response.TransmitFile(strS);
Response.End();
//Response.WriteFile(strS);
Response.Flush();
Response.Clear();

}

}

This code doesn't work if paging is enabled in GridView and the other this is cloumns become of variable width in PDF document , to fix these issues read my next Post Exporting Paging enabled GridView to PDF using iTextSharp

Download the sample Code


Other Gridview articles you would like to read:
1. Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

2. Pouplating Multiple DetailsView based on single GridView using DataKeyNames in ASP.NET

3. Merging GridView Headers to have multiple Headers in GridView using C# ASP.NET