Thursday, November 1, 2012

GridView Filter Expression With DropDownList ASP.NET

This example explains how to Filter GridView With DropDownList In ASP.NET Using FilterExpression And Filter Paramaters Or GridView Filtering with Sql Server And SqlDataSource.


Filter GridView With DropDownList In ASP.NET
I m using northwind database and customers table to show data and filter gridview with dropdownlist.

First of all open aspx page in design view and place 2 dropdownlist, 1 gridview and 3 SqlDatasource on the page.

Configure all 3 sqldatasources as according to code mentioned below. and use them for datasource to populate city dropdown, country dropdown and gridview.

You can also read ModalPopUp extender in Gridview to know how to configure SqlDataSource.


HTML Markup to Populate Dropdowns
<asp:DropDownList ID="ddlCity" runat="server" 
                  AppendDataBoundItems="True" 
                  AutoPostBack="True" 
                  DataSourceID="sqlDataSourceCity" 
                  DataTextField="City" 
                  DataValueField="City" Width="100px">
 <asp:ListItem Value="%">All</asp:ListItem>
 </asp:DropDownList>

<asp:SqlDataSource ID="sqlDataSourceCity" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT DISTINCT City FROM Customers">
</asp:SqlDataSource>


<asp:DropDownList ID="ddlCountry" runat="server" 
                  AppendDataBoundItems="True" 
                  AutoPostBack="True" 
                  DataSourceID="sqlDataSourceCountry" 
                  DataTextField="Country" 
                  DataValueField="Country" Width="100px">
<asp:ListItem Value="%">All</asp:ListItem>
</asp:DropDownList>


<asp:SqlDataSource ID="sqlDataSourceCountry" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT DISTINCT [Country] FROM [Customers]">
</asp:SqlDataSource>

Now Configure third sqldatasource to populate gridview based on filter expression as mentioned below

HTML markup of gridview and sqldatasource with filter expression
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" 
              DataSourceID="sqlDataSourceGridView" 
              AutoGenerateColumns="False"
              CssClass="GridViewStyle" 
              GridLines="None" Width="650px" 
              ShowHeader="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Customer ID"/>
<asp:BoundField DataField="CompanyName" HeaderText="Company"/>
<asp:BoundField DataField="ContactName" HeaderText="Name"/>
<asp:BoundField DataField="City" HeaderText="city"/>
<asp:BoundField DataField="Country" HeaderText="Country"/>
</Columns>
</asp:GridView>


<asp:SqlDataSource ID="sqlDataSourceGridView" 
                   runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], 
[City], [Country] FROM [Customers]" 
FilterExpression="[City] like '{0}%' and [Country] like '{1}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlCity" Name="City" 
                      PropertyName="SelectedValue" 
                      Type="String" />
<asp:ControlParameter ControlID="ddlCountry" Name="Country" 
                      PropertyName="SelectedValue" 
                      Type="String" />
</FilterParameters>
</asp:SqlDataSource>

Build and run the application.

Download Sample Code

GridView Filter Expression With DropDownList ASP.NET

This example explains how to Filter GridView With DropDownList In ASP.NET Using FilterExpression And Filter Paramaters Or GridView Filtering with Sql Server And SqlDataSource.


Filter GridView With DropDownList In ASP.NET
I m using northwind database and customers table to show data and filter gridview with dropdownlist.

First of all open aspx page in design view and place 2 dropdownlist, 1 gridview and 3 SqlDatasource on the page.

Configure all 3 sqldatasources as according to code mentioned below. and use them for datasource to populate city dropdown, country dropdown and gridview.

You can also read ModalPopUp extender in Gridview to know how to configure SqlDataSource.


HTML Markup to Populate Dropdowns
<asp:DropDownList ID="ddlCity" runat="server" 
                  AppendDataBoundItems="True" 
                  AutoPostBack="True" 
                  DataSourceID="sqlDataSourceCity" 
                  DataTextField="City" 
                  DataValueField="City" Width="100px">
 <asp:ListItem Value="%">All</asp:ListItem>
 </asp:DropDownList>

<asp:SqlDataSource ID="sqlDataSourceCity" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT DISTINCT City FROM Customers">
</asp:SqlDataSource>


<asp:DropDownList ID="ddlCountry" runat="server" 
                  AppendDataBoundItems="True" 
                  AutoPostBack="True" 
                  DataSourceID="sqlDataSourceCountry" 
                  DataTextField="Country" 
                  DataValueField="Country" Width="100px">
<asp:ListItem Value="%">All</asp:ListItem>
</asp:DropDownList>


<asp:SqlDataSource ID="sqlDataSourceCountry" runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT DISTINCT [Country] FROM [Customers]">
</asp:SqlDataSource>

Now Configure third sqldatasource to populate gridview based on filter expression as mentioned below

HTML markup of gridview and sqldatasource with filter expression
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" 
              DataSourceID="sqlDataSourceGridView" 
              AutoGenerateColumns="False"
              CssClass="GridViewStyle" 
              GridLines="None" Width="650px" 
              ShowHeader="false">
<Columns>
<asp:BoundField DataField="CustomerID" HeaderText="Customer ID"/>
<asp:BoundField DataField="CompanyName" HeaderText="Company"/>
<asp:BoundField DataField="ContactName" HeaderText="Name"/>
<asp:BoundField DataField="City" HeaderText="city"/>
<asp:BoundField DataField="Country" HeaderText="Country"/>
</Columns>
</asp:GridView>


<asp:SqlDataSource ID="sqlDataSourceGridView" 
                   runat="server" 
ConnectionString="<%$ ConnectionStrings:northWindConnectionString %>" 
SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName], 
[City], [Country] FROM [Customers]" 
FilterExpression="[City] like '{0}%' and [Country] like '{1}%'">
<FilterParameters>
<asp:ControlParameter ControlID="ddlCity" Name="City" 
                      PropertyName="SelectedValue" 
                      Type="String" />
<asp:ControlParameter ControlID="ddlCountry" Name="Country" 
                      PropertyName="SelectedValue" 
                      Type="String" />
</FilterParameters>
</asp:SqlDataSource>

Build and run the application.

Download Sample Code

Display Images In GridView From DataBase Asp.Net

In this example i am explaining how to Show Display Images In GridView From DataBase In ASP.NET Using C# And VB.NET or showing images stored or saved in SQL Server database in gridview,For this i've already stored images in Database.

Table schema is shown below, ID column is primary key with Identity increment,datatype of Image column is Binary.


Display Images In GridView From DataBase Asp.Net
To know how to save or store Images in DataBase visit link below

Upload/Save Images in Database using FileUpload Control in ASP.NET C# VB.NET


For displaying images in gridview we need to create a Handler to read binary data from database.
Right click on solution explorer and Add new item, Pick Generic Handler and name it Handler.ashx.
Write this code in ProcessRequest method
C# code behind
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;

public class Handler : IHttpHandler {
    
public void ProcessRequest (HttpContext context) 
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings
                      ["ConnectionString"].ConnectionString;

// Create SQL Command 
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "Select ImageName,Image from Images" + 
                  " where ID =@ID";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;

SqlParameter ImageID = new SqlParameter
                    ("@ID", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["ID"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
dReader.Read();
context.Response.BinaryWrite((byte[])dReader["Image"]);
dReader.Close();
con.Close();
}

VB.NET Code
Public Class Handler
    Implements IHttpHandler
    
Public Sub ProcessRequest(ByVal context As HttpContext)
Dim con As New SqlConnection()
con.ConnectionString = ConfigurationManager.ConnectionStrings
                        ("ConnectionString").ConnectionString
        
        ' Create SQL Command 
        
        Dim cmd As New SqlCommand()
        cmd.CommandText = "Select ImageName,Image from Images" +
                          " where ID =@IID"
        cmd.CommandType = System.Data.CommandType.Text
        cmd.Connection = con
        
        Dim ImageID As New SqlParameter
                             ("@IID", System.Data.SqlDbType.Int)
        ImageID.Value = context.Request.QueryString("ID")
        cmd.Parameters.Add(ImageID)
        con.Open()
        Dim dReader As SqlDataReader = cmd.ExecuteReader()
        dReader.Read()
        context.Response.BinaryWrite
                    (DirectCast(dReader("Image"), Byte()))
        dReader.Close()
        con.Close()
    End Sub
End Class

Now drag a GridView control on the aspx page and add SQLDataSource to it.

For configuring GridVIew with SqlDataSource read
Insert Delete Update records in GridView using SqlDataSource ItemTemplate and EditItemTemplate

Now go to html markup of GridView and add a TemplateField and in ItemTemplate add a Image control to display Images.
Html Source of GridView should look like this
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="ID"
              DataSourceID="SqlDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" 
                InsertVisible="False" ReadOnly="True"
                               SortExpression="ID" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName" 
                               SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
           ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [ImageName], [Image] 
              FROM [Images]"></asp:SqlDataSource>

For VB.NET there is slight change in html markup of page
change below mentioned line
ImageUrl='<%# "Handler.ashx?ID=" + Eval("ID")%>'/>

to

ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")%>'/>

THis is how it will look

If you want to display Images in multiple columns or in more than one clumns of GridView then u need to make changes in the code as mentioned below.

1. Add a new column in database (i've named it Image2)
2. Add one mote Template Field in html source of gridview and change source as below
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=1"%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image2">
<ItemTemplate>
<asp:Image ID="Image2" runat="server" 
ImageUrl='<%# Eval("ID", "Handler.ashx?ID={0}")+"&img=2"%>'/>
</ItemTemplate>
</asp:TemplateField>

And make these changes in code behind of handler.ashx
//Add this line of code in handler.ashx
int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
//Now change earlier code to this one 
SqlDataReader dReader = cmd.ExecuteReader();
        dReader.Read();
        if (intImg == 1)
        {
            context.Response.BinaryWrite((byte[])dReader["Image"]);
        }
        else if (intImg == 2)
        {
            context.Response.BinaryWrite((byte[])dReader["Image2"]);
        }
        dReader.Close();
        con.Close();
Now it will look like this


hope this helps.

Download sample code attached

Sample code for displaying Images in Multiple columns




Other GridView articles:
ASP.NET Display Images in Gridview/DataList using objectdatasource

ASP.NET Insert Edit Update GridView with ObjectDataSource

Add AutoNumber Column in GridView or DataList

Creating Shopping cart in ASP.NET C# VB.NET Example using DataList GridView

Ajax autocomplete extender textbox in EditItemTemaplate of GridView

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

In this example i am going to demonstrate how to Display Running Total In GridView Footer Row In ASP.NET using C# and VB.NET. This method works with paging enabled gridview as well.


Running Total In Gridview Footer In ASP.NET

For demo purpose gridview is populated using sqldatasource having table with columns ID ,Name,Amount

I m showing total of amount column is gridview footer. for this we need to sum the the column in RowDataBound Even of Gridiew

Html source of gridview is
<asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False"
              DataKeyNames="ID" DataSourceID="SqlDataSource1" 
              OnRowDataBound="GridView1_RowDataBound" 
              ShowFooter="True" AllowPaging="True" PageSize="5" 
              BackColor="#ffffff" BorderColor="AliceBlue" 
              BorderStyle="None" BorderWidth="1px" 
              CellPadding="3" 
              CellSpacing="2" FooterStyle-BackColor="#da821e" 
              FooterStyle-ForeColor="#ffffff" 
              RowStyle-BackColor="#003366" 
              RowStyle-ForeColor="#ffffff" 
              AlternatingRowStyle-BackColor="#da821e">
<Columns>
     <asp:BoundField DataField="ID" HeaderText="ID" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="ID" />
     <asp:BoundField DataField="Name" HeaderText="Name" 
                     InsertVisible="False" ReadOnly="True"
                     SortExpression="Name" FooterText="Total"/>
     <asp:TemplateField HeaderText="Amount">
     <ItemTemplate>
     <asp:Label ID="lblAmount" runat="server" 
                Text='<%# "$"+Eval("Amount").ToString()%>'>
     </asp:Label>
     </ItemTemplate>
     <FooterTemplate>
     <asp:Label ID="lblTotal" runat="server"></asp:Label>
     </FooterTemplate>
     </asp:TemplateField>
     </Columns>
     <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
     <HeaderStyle BackColor="#da821e" Font-Bold="True" 
                  ForeColor="White" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Amount] FROM [Expenses]">
</asp:SqlDataSource>
Now we need to write code for summing the column in RowdataBound Even of GridView

C# code behind
public partial class _Default : System.Web.UI.Page 
{
    decimal grdTotal = 0;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
protected void GridView1_RowDataBound
                   (object sender, GridViewRowEventArgs e)
{
 if (e.Row.RowType == DataControlRowType.DataRow)
 {
  decimal rowTotal = Convert.ToDecimal
              (DataBinder.Eval(e.Row.DataItem, "Amount"));
  grdTotal = grdTotal + rowTotal;
 }
 if (e.Row.RowType == DataControlRowType.Footer)
 {
  Label lbl = (Label)e.Row.FindControl("lblTotal");
  lbl.Text = grdTotal.ToString("c");
 }
}
}


VB.NET code behind
Public Partial Class _Default
    Inherits System.Web.UI.Page
    Private grdTotal As Decimal = 0
    Protected Sub Page_Load
    (ByVal sender As Object, ByVal e As EventArgs)
        
End Sub

Protected Sub GridView1_RowDataBound
(ByVal sender As Object, ByVal e As GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then
Dim rowTotal As Decimal = 
Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "Amount"))
grdTotal = grdTotal + rowTotal
End If

If e.Row.RowType = DataControlRowType.Footer Then
Dim lbl As Label = DirectCast(e.Row.FindControl
                           ("lblTotal"), Label)
lbl.Text = grdTotal.ToString("c")
End If
End Sub
End Class


Hope this helps

Other gridview articles:
Populating dropdown based on the selection of first drop down in DetailsView using FindControl and ItemTemplate

Pouplating Multiple DetailsView based on single GridView using DataKeyNames

Merging GridView Headers to have multiple Headers in GridView

Search Records In GridView And Highlight Results Using AJAX ASP.NET

Insert update Delete record in GridView using SqlDataSource ItemTemplate and EditItemTemplate

AutoNumber Column In GridView DataList ASP.NET

This example explains how to Add AutoNumber Column In GridView Or DataList In ASP.NET 2.0,3.5,4.0 Using C# And VB.NET. Several times we need to display Auto Number or serial number for Rows records in gridview or other similar controls in ASP.NET.

We can add AutoNumber column by using Container.DataItemIndex property in html markup of the Gridview.



Here's the sample html markup for the page

<title>Auto Number Cloumn in GridView </title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" 
              AllowPaging="True" AutoGenerateColumns="False"
              DataSourceID="SqlDataSource1" PageSize="6" 
              AlternatingRowStyle-BackColor="#006699" 
              AlternatingRowStyle-ForeColor="#FFFFFF" >
    <Columns>
    <asp:TemplateField HeaderText="Serial Number">
    <ItemTemplate>
        <%# Container.DataItemIndex + 1 %>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Name" HeaderText="Name" 
                    SortExpression="Name" />
    <asp:BoundField DataField="Location" HeaderText="Location" 
                    SortExpression="Location" />
    </Columns>
    </asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [Name], [Location] FROM [Details]">
</asp:SqlDataSource>

Hope this helps

Search Records In GridView And Highlight Results Asp.Net Ajax

In this example i am Explaining how to Search Records In GridView And Highlight Results Using Ajax In Asp.Net 2.0,3.5,4.0 based on text entered in textbox.



Add following CSS style in head section of page.

HTML SOURCE
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
    
Enter first name to search:
 
<asp:TextBox ID="txtSearch" runat="server" AutoPostBack="True"
             OnTextChanged="txtSearch_TextChanged"/>
 
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="grdSearch" runat="server"
              AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="FirstName">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" 
           Text='<%# Highlight(Eval("FirstName").ToString()) %>'/>
</ItemTemplate>
</asp:TemplateField>
 
<asp:TemplateField HeaderText="LastName">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#(Eval("LastName")) %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#(Eval("Location")) %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="txtSearch" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>

Write following code in code behind
C# CODE
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGrid();
        }
    }
    private DataTable GetRecords()
    {
        SqlConnection conn = new SqlConnection(strConnection);
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Select * from Employees";
        SqlDataAdapter dAdapter = new SqlDataAdapter();
        dAdapter.SelectCommand = cmd;
        DataSet objDs = new DataSet();
        dAdapter.Fill(objDs);
        return objDs.Tables[0];

    }
    private void BindGrid()
    {
        DataTable dt = GetRecords();
        if (dt.Rows.Count > 0)
        {
            grdSearch.DataSource = dt;
            grdSearch.DataBind();
        }
    }
    private void SearchText()
    {
        DataTable dt = GetRecords();
        DataView dv = new DataView(dt);
        string SearchExpression = null;
        if (!String.IsNullOrEmpty(txtSearch.Text))
        {
            SearchExpression = string.Format("{0} '%{1}%'",
            grdSearch.SortExpression, txtSearch.Text);

        }
        dv.RowFilter = "FirstName like" + SearchExpression;
        grdSearch.DataSource = dv;
        grdSearch.DataBind();

    }
    public string Highlight(string InputTxt)
    {
        string Search_Str = txtSearch.Text.ToString();
        // Setup the regular expression and add the Or operator.
        Regex RegExp = new Regex(Search_Str.Replace(" ", "|").Trim(),
        RegexOptions.IgnoreCase);

        // Highlight keywords by calling the 
        //delegate each time a keyword is found.
        return RegExp.Replace(InputTxt,
        new MatchEvaluator(ReplaceKeyWords));

        // Set the RegExp to null.
        RegExp = null;

    }

    public string ReplaceKeyWords(Match m)
    {

       // return "" + m.Value + "";

    }

    protected void txtSearch_TextChanged(object sender, EventArgs e)
    {
        SearchText();
    }

VB.NET
Protected Sub Page_Load(sender As Object, e As EventArgs)
 If Not IsPostBack Then
  BindGrid()
 End If
End Sub
Private Function GetRecords() As DataTable
 Dim conn As New SqlConnection(strConnection)
 conn.Open()
 Dim cmd As New SqlCommand()
 cmd.Connection = conn
 cmd.CommandType = CommandType.Text
 cmd.CommandText = "Select * from Employees"
 Dim dAdapter As New SqlDataAdapter()
 dAdapter.SelectCommand = cmd
 Dim objDs As New DataSet()
 dAdapter.Fill(objDs)
 Return objDs.Tables(0)

End Function
Private Sub BindGrid()
 Dim dt As DataTable = GetRecords()
 If dt.Rows.Count > 0 Then
  grdSearch.DataSource = dt
  grdSearch.DataBind()
 End If
End Sub
Private Sub SearchText()
 Dim dt As DataTable = GetRecords()
 Dim dv As New DataView(dt)
 Dim SearchExpression As String = Nothing
 If Not [String].IsNullOrEmpty(txtSearch.Text) Then

  SearchExpression = String.Format("{0} '%{1}%'", grdSearch.SortExpression, txtSearch.Text)
 End If
 dv.RowFilter = "FirstName like" & SearchExpression
 grdSearch.DataSource = dv
 grdSearch.DataBind()

End Sub
Public Function Highlight(InputTxt As String) As String
 Dim Search_Str As String = txtSearch.Text.ToString()
 ' Setup the regular expression and add the Or operator.
 Dim RegExp As New Regex(Search_Str.Replace(" ", "|").Trim(), RegexOptions.IgnoreCase)

 ' Highlight keywords by calling the 
 'delegate each time a keyword is found.
 Return RegExp.Replace(InputTxt, New MatchEvaluator(AddressOf ReplaceKeyWords))

 ' Set the RegExp to null.
 RegExp = Nothing

End Function

Public Function ReplaceKeyWords(m As Match) As String

 Return "" & Convert.ToString(m.Value) & ""

End Function

Protected Sub txtSearch_TextChanged(sender As Object, e As EventArgs)
 SearchText()
End Sub

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