Pages

22 Aug 2013

SQL Server DateTime Formatting

The Transact-SQL (T-SQL) Convert command can be used to convert data between different types. When converting a DATETIME value to a VarChar string value a style code may be applied. The following code uses style code 2 to indicate that an ANSI standard date (yy.mm.dd) should be used to represent the date as a string.

SELECT convert(VARCHAR, getdate(), 2)


Converting a VarChar to a DateTime

The date style code can be equally important when converting a VarChar to a DateTime. The following sample is using ANSI date format so 09.08.29 represents 29 August 2009. Without the style specified, the resultant DateTime could be converted as 9 August 2029 or 8 September 2029.


SELECT convert(DATETIME, '09.08.29', 2)


The table below describes the most popular style codes that are available for use when converting between a DateTime and a character representation. Each example uses today's date, 8 September 2007.
Style CodeStyleFormatExample
0 or 100Default. Equivalent to not specifying a style code.mon dd yyyy hh:mmAMSep 8 2007 9:00PM
1USA date.mm/dd/yy09/08/07
2ANSI date.yy.mm.dd07.09.08
3UK / French date.dd/mm/yy08/09/07
4German date.dd.mm.yy08.09.07
5Italian date.dd-mm-yy08-09-07
6Abbreviated month.dd mmm yy08 Sep 07
7Abbreviated month.mmm dd, yySep 08, 07
8 or 10824 hour time.HH:mm:ss21:00:00
9 or 109Default formatting with seconds and milliseconds appended.mon dd yyyy hh:mm:ss:fffAMSep 8 2007 9:00:00:000PM
10USA date with hyphen separators.mm-dd-yy09-08-07
11Japanese date.yy/mm/dd07/09/08
12ISO date.yymmdd070908
13 or 113European default with seconds and milliseconds.dd mon yyyy HH:mm:ss:fff08 Sep 2007 21:00:00:000
14 or 11424 hour time with milliseconds.HH:mm:ss:fff21:00:00:000
20 or 120ODBC canonical date and time.yyyy-mm-dd HH:mm:ss2007-09-08 21:00:00
21 or 121ODBC canonical date and time with milliseconds.yyyy-mm-dd HH:mm:ss.fff2007-09-08 21:00:00.000
101USA date with century.mm/dd/yyyy09/08/2007
102ANSI date with century.yyyy.mm.dd2007/09/08
103UK / French date with century.dd/mm/yyyy08/09/2007
104German date with century.dd.mm.yyyy08.09.2007
105Italian date with century.dd-mm-yyyy08-09-2007
106Abbreviated month with century.dd mmm yyyy08 Sep 2007
107Abbreviated month with century.mmm dd, yyyySep 08, 2007
110USA date with hyphen separators and century.mm-dd-yyyy09-08-2007
111Japanese date with century.yyyy/mm/dd2007/09/08
112ISO date with century.yymmdd20070908
126ISO8601, for use in XML.yyy-mm-ddThh:mm:ss2007-09-08T21:00:00
Converting a DateTime to a VarChar
DateTime Style Codes

Echo (PHP) vs Print (PHP)

Echo (PHP) vs Print (PHP)

Comparison chart


Echo (PHP)Print (PHP)
Parameters:echo can take more than oneparameter when used without parentheses. The syntax is echo expression [, expression[, expression] ... ]. Note that echo ($arg1,$arg2) is invalid.print only takes one parameter.
Return value:echo does not return any valueprint always returns 1 (integer)
Syntax:void echo ( string $arg1 [, string $... ] )int print ( string $arg )
What is it?:In PHP, echo is not a function but a language construct.In PHP, print is not a really function but a language construct. However, it behaves like a function in that it returns a value.

Displaying Date and Time in PHP Code

The date and time we will show how to display in this tutorial is the one specified by the server which is hosting our pages. In case you want to display a different date or time (p. e.,  your clients are mostly from Belgium but your server is located in US and you want to display the local time in Belgium) you will find how to do it  latter on this page.

In the table bellow we have include the PHP code necessary to display one by one all the time and date related information. By copying the code in the first column to your page you will get the data which is explained in the third column. The  column in the middle is the value of those data the day we were preparing this page.  

Code Output
<?php print  date("a"); ?> pm "am" or "pm"
<?php print  date("A"); ?> PM "AM" or "PM"
<?php print  date("d"); ?> 15 Day of the month: 01 to 31
<?php print  date("D"); ?> Tue Day of the week: Sun, Mon, Tue, Wed, Thu, Fri, Sat
<?php print  date("F"); ?> October Month: January, February, March...
<?php print  date("h"); ?> 03 Hour: 01 to 12
<?php print  date("H"); ?> 15 Hour: 00 to 23
<?php print  date("g"); ?> 3 Hour: 1 to 12
<?php print  date("G"); ?> 15 Hour: 0 to 23
<?php print  date("i"); ?> 26 Minutes: 00 to 59
<?php print  date("j"); ?> 15 Day of the month: 1 to 31
<?php print  date("l"); ?> Tuesday Day of the week: Sunday, Monday, Tuesday...
<?php print  date("L"); ?> 0 Is it a leap year? 1 (yes) or 0 (no)
<?php print  date("m"); ?> 10 Month: 01 to 12
<?php print  date("n"); ?> 10 Month: 1 to 12
<?php print  date("M"); ?> Oct Month: Jan, Feb, Mar, Apr, May...
<?php print  date("s"); ?> 03 Seconds: 00 to 59
<?php print  date("S"); ?> th Ordinal: 1st, 2st, 3st, 4st... Need to be used with a numeric time/date value. See latter.
<?php print  date("t"); ?> 31 Number of days in the month: 28 to 31
<?php print  date("U"); ?> 1034691963 Seconds since 1970/01/01 00:00:00
<?php print  date("w"); ?> 2 Day of the week: 0 (Sunday) to 6 (Saturday)
<?php print  date("Y"); ?> 2002 Year (four digits)
<?php print  date("y"); ?> 02 Year (two digits)
<?php print  date("z"); ?> 287 Day of the year: 0 to 365
<?php print  date("Z"); ?> -21600 Difference in seconds from Greenwhich meridian
As shown in the table the commands we are using in all case are "print" (in order to show the values to the visitor) and "date" (which will allow us to get the data corresponding to the string code we are using between brakets).

So we already know how to obtain the data and how to show it  in our page, but if we want to display different values simultaneously, we have at least three option:


The code
Output
<?php print  date("Y"); ?>:<?php print  date("m"); ?>: <?php print  date("d"); ?> 2002:10:15
<?php print  date("Y").":".date("m").":".date("d"); ?>
2002:10:15
<?php print  date("Y:m:d"); ?>
2002:10:15
The first option is very easy to understand (we have just copied the code from the table one by one). The second option concatenates the data basically in the same way, and the third one is probably the most useful system, but the one we must understand before using it.

Command  "date" will get the data we want to display, and that data is specified by the string used within data (in our case: "Y:m:d"). Each character in this string may or may not have a meaning depending upon there is or there is not a value asociate with that letter (see the first table in this page). In our case some characters will be replaced by its corresponding value:


Y
:
m
:
d    
Year (four digits)
no meaning
Month: 01 to 12
no meaning
Day of the month: 01 to 31

Check this usefull examples:

The code
Output
<?php print  date("Y:m:d H:i") ?> 2002:10:15 15:26
<?php print  date("l dS of F Y h:i:s A"); ?>
Tuesday 15th of October 2002 15:26:03 PM
The time is <?php print  date("H:i") ?>.
That means it's <?php print  date("i") ?>
minutes past <?php print  date("H") ?> o'clock.
The time is 15:26. That means it's 26 minutes past 15 o'clock.


Take care when using date command or you may get unwanted data as shown in the first row in the table bellow (use the code in second row instead):

The code
Output
Character with meaning
<?php print  date("Today is l"); ?> WETo15pm02 2603 Tuesday The following characters have a meaning: T, d, a, y, i, s,  l
<?php print  "Today is ".date("l"); ?>
Today is Tuesday Only data asociated to "l" (day of the week) is requested


Example: Link of the Day

What if you wanted to have a link that points to a different page every day of the week? Here's how you can do that. First, create one page for each day of the week and name them "Sunday.htm," "Monday.htm," and so on.
To make the link, copy the code bellow to your page
<a href= <?php print  date("l"); ?>.htm>Link of the Day</a>


Place the code in your ".php" page where you want it to appear. When you click this link in your browser, it will take you to the "Link of the Day".

Using "S" with date comand.

Lets suppose we are using the code bellow in different consecutive days:


Day
Code
Output
2002/01/01
<? php print  date("nS of F"); ?>
1st of January
2002/01/02
<? php print  date("nS of F"); ?>
2nd of January
2002/01/03
<? php print  date("nS of F"); ?>
3rd of January
2002/01/04
<? php print  date("nS of F"); ?>
4th of January
The "S" character included within command date will allow us to show "st", "nd", "rd" or "th" values depending on the number preceding the character "S".


Displaying local time

In this tutorial we will consider our server is located in a different time zone from the one our clients are located at (a Belgium related site is in a server located is USA for example).

First we must know the time in the server. We will create a text file with the code bellow, and we will copy it to our server:

Time in server: <?php print  date("H:i") ?>
Then we will visit our page and we will get the time in the server. Let suppose the time is 16:00

Second, we will calculate the difference in hours between local time and the time in server. Let suppose the time in Belgium is 20:00, so the difference is 4 hours.
To get the local time we will use the code in the table bellow:

<?php
$differencetolocaltime=4;
$new_U=date("U")-$differencetolocaltime*3600;
print date("H:i", $new_U);
?>
Lets explain this code:

We have create a variable named $differencetolocaltime, and we have stablish the value for this variable (4)
In third line of the script we have create a variable named $new_U, and the value for this variable will be 'date("U")' (Seconds since 1970/01/01 00:00:00) to which we have substracted the difference of hours between the two time zones (in our case 4 hours, which is the value for the variable $differencetolocaltime, has been multiplied by 3600, which is the number of seconds in one hour)
In the last step we have write to the document the new hour and time by using "date" command to which we have let know the exact date (specified by $new_U) from which we want to get the time (if it is not specified, as for example when using 'date("H:i")', the time and date in the server will be displayed as shown before in this page).

21 Aug 2013

CHANGE GRIDVIEW ROW COLOR ON MOUSEOVER IN ASP.NET WITH JQUERY

In this article I will explain how to change GridView Row Background Color on MouseOver ( Hover ) using jQuery and JavaScript in ASP.Net
In one of my previous articles I have explained Change GridView Row Color OnClick without PostBack in ASP.Net

HTML Markup
The HTML Markup consists of an ASP.Net GridView with two columns.
<asp:GridView ID="GridView1" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
    runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
    </Columns>
</asp:GridView>


Namespaces
You will need to import the following namespaces.
using System.Data;


Binding the GridView
I have made use of DataTable with some dummy values for this article.
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
        dt.Rows.Add(1, "John Hammond", "United States");
        dt.Rows.Add(2, "Mudassar Khan", "India");
        dt.Rows.Add(3, "Suzanne Mathews", "France");
        dt.Rows.Add(4, "Robert Schidner", "Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}


Changing the GridView Row Background color when clicked using JavaScript
In the below JavaScript code snippet, I have made use of jQuery to make the job easier.  Firstly I have attached jQuery Hover event handler to the TD i.e. Cell of the GridView. When mouse is moved over some GridView Cell within a Row, using the reference of the Cell the Row of the GridView is determined.
Then the hover_row CSS class is applied to the Row to which the Cell belongs i.e. the Current Row on which the mouse was hovered, this is implemented using the closest function of jQuery which can be used to determine the closest parent here the closest TR element.
The hover_row CSS class is used to apply color to the GridView Row.
<script type="text/javascript">
    $(function () {
        $("[id*=GridView1] td").hover(function () {
            $("td", $(this).closest("tr")).addClass("hover_row");
        },function(){
            $("td", $(this).closest("tr")).removeClass("hover_row");
        });
    });
</script>



CSS Classes used to style the GridView
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
    td
    {
        cursor: pointer;
    }
    .hover_row
    {
        background-color: #A1DCF2;
    }
</style>

ASP.Net: Getting DataKey from GridView on Edit and Delete


The GridView control has one of the columns set as its DataKey. When a row is Selected, it fires the Selected event handler and I can use myGridView.SelectedDataKey.Value to get the value of the DataKey column for the selected row.

However, the event handler for when a row is Edited or Deleted does not seem to have a mechanism to get the DataKey value for the row in question. The event arg parameter for these event handlers contains the index of the row in the GridView but I'm specifically after the DataKey value.


protected void gridQuestion_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int id = (int)grdQuestions.DataKeys[e.RowIndex].Value;

    }

Simple Insert-Select-Edit-Update and Delete in ASP.Net GridView control

Basically I have tried to make the normal Add (Insert), Edit, Update and delete functions in ASP.Net GridView simple and also combining the powers of ASP.Net AJAX with that of JQuery to give an elegant and charming user experience.

Below is the connection string from the web.config

<connectionStrings>
      <add name="conString" connectionString="Data Source=.\SQLExpress;
      database=Northwind;Integrated Security=true"/>
connectionStrings>


The GridView

Below is the markup of the ASP.Net GridView control that I’ll be using to demonstrate the various features explained in this article.


<div id = "dvGrid" style ="padding:10px;width:550px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server"  Width = "550px"
AutoGenerateColumns = "false" Font-Names = "Arial"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" 
HeaderStyle-BackColor = "green" AllowPaging ="true"  ShowFooter = "true" 
OnPageIndexChanging = "OnPaging" onrowediting="EditCustomer"
onrowupdating="UpdateCustomer"  onrowcancelingedit="CancelEdit"
PageSize = "10" >
<Columns>
<asp:TemplateField ItemStyle-Width = "30px"  HeaderText = "CustomerID">
    <ItemTemplate>
        <asp:Label ID="lblCustomerID" runat="server"
        Text='<%# Eval("CustomerID")%>'>asp:Label>
    ItemTemplate>
    <FooterTemplate>
        <asp:TextBox ID="txtCustomerID" Width = "40px"
            MaxLength = "5" runat="server">asp:TextBox>
    FooterTemplate>
asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "100px"  HeaderText = "Name">
    <ItemTemplate>
        <asp:Label ID="lblContactName" runat="server"
                Text='<%# Eval("ContactName")%>'>asp:Label>
    ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtContactName" runat="server"
            Text='<%# Eval("ContactName")%>'>asp:TextBox>
    EditItemTemplate> 
    <FooterTemplate>
        <asp:TextBox ID="txtContactName" runat="server">asp:TextBox>
    FooterTemplate>
asp:TemplateField>
<asp:TemplateField ItemStyle-Width = "150px"  HeaderText = "Company">
    <ItemTemplate>
        <asp:Label ID="lblCompany" runat="server"
            Text='<%# Eval("CompanyName")%>'>asp:Label>
    ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="txtCompany" runat="server"
            Text='<%# Eval("CompanyName")%>'>asp:TextBox>
    EditItemTemplate> 
    <FooterTemplate>
        <asp:TextBox ID="txtCompany" runat="server">asp:TextBox>
    FooterTemplate>
asp:TemplateField>
<asp:TemplateField>
    <ItemTemplate>
        <asp:LinkButton ID="lnkRemove" runat="server"
            CommandArgument = '<%# Eval("CustomerID")%>'
         OnClientClick = "return confirm('Do you want to delete?')"
        Text = "Delete" OnClick = "DeleteCustomer">asp:LinkButton>
    ItemTemplate>
    <FooterTemplate>
        <asp:Button ID="btnAdd" runat="server" Text="Add"
            OnClick = "AddNewCustomer" />
    FooterTemplate>
asp:TemplateField>
<asp:CommandField  ShowEditButton="True" />
Columns>
<AlternatingRowStyle BackColor="#C2D69B"  />
asp:GridView>
ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID = "GridView1" />
Triggers>
asp:UpdatePanel>
div>

The GridView has 3 data columns

1. Customer ID

2. Contact Name

3. Company Name

I have added a LinkButton in 4th column which will act as custom column for delete functionality. The reason to use a custom button is to provide the JavaScript confirmation box to the user when he clicks Delete. For Edit and Update I have added a command field which will act as the 5th column.

There’s also a Footer Row with 3 TextBoxes which will be used to add new records to the database and an Add button which will be used to add the records.


I have enabled pagination and finally wrapped the complete Grid in update panel and the update panel in a div dvGrid and the reason to that I’ll explain later in the article


Binding the GridView

Below is the code to bind the GridView in the page load event of the page

C# Code

private String strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindData();
    }
}

private void BindData()
{
    string strQuery = "select CustomerID,ContactName,CompanyName" +
                       " from customers";
    SqlCommand cmd = new SqlCommand(strQuery);
    GridView1.DataSource = GetData(cmd);
    GridView1.DataBind();

}

VB Code

Private strConnString As String = ConfigurationManager.ConnectionStrings("conString").ConnectionString
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
   If Not IsPostBack Then
         BindData()
   End If
End Sub

Private Sub BindData()
  Dim strQuery As String = "select CustomerID,ContactName,CompanyName" & _
                                " from customers"
  Dim cmd As New SqlCommand(strQuery)
  GridView1.DataSource = GetData(cmd)
  GridView1.DataBind()

End Sub

Below is the screenshot of the GridView being populated using the above code




Adding new record

As discussed above I have placed 3 textboxes and a button in the Footer Row of the ASP.Net GridView control in order to add new record to the database. On the onclick event if the button the records are inserted into the SQL Server Database and the GridView is updated



C#

protected void AddNewCustomer(object sender, EventArgs e)
{
  string CustomerID=((TextBox)GridView1.FooterRow.FindControl("txtCustomerID")).Text;
  string Name = ((TextBox)GridView1.FooterRow.FindControl("txtContactName")).Text;
  string Company = ((TextBox)GridView1.FooterRow.FindControl("txtCompany")).Text;
  SqlConnection con = new SqlConnection(strConnString);
  SqlCommand cmd = new SqlCommand();
  cmd.CommandType = CommandType.Text;
  cmd.CommandText = "insert into customers(CustomerID, ContactName, CompanyName) " +
  "values(@CustomerID, @ContactName, @CompanyName);" +
  "select CustomerID,ContactName,CompanyName from customers";
  cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
  cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
  cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
  GridView1.DataSource = GetData(cmd);
  GridView1.DataBind();
}



VB.Net

Protected Sub AddNewCustomer(ByVal sender As Object, ByVal e As EventArgs)
   Dim CustomerID As String = DirectCast(GridView1.FooterRow _
                .FindControl("txtCustomerID"), TextBox).Text
   Dim Name As String = DirectCast(GridView1 _
                .FooterRow.FindControl("txtContactName"), TextBox).Text
   Dim Company As String = DirectCast(GridView1 _
                .FooterRow.FindControl("txtCompany"), TextBox).Text
   Dim con As New SqlConnection(strConnString)
   Dim cmd As New SqlCommand()
   cmd.CommandType = CommandType.Text
   cmd.CommandText = "insert into customers(CustomerID, ContactName, " & _
        "CompanyName) values(@CustomerID, @ContactName, @CompanyName);" & _
        "select CustomerID,ContactName,CompanyName from customers"
   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID
   cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name
   cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company
   GridView1.DataSource = GetData(cmd)
   GridView1.DataBind()
End Sub


You will notice I am firing two queries one to insert the data and second to select the updated data and then rebind the GridView. The figure below displays how new records are added.


Edit and Update existing records

As described above I have used command field in order to provide the Edit functionality. Below is the code snippet which is used to edit and update the records



C#

protected void EditCustomer(object sender, GridViewEditEventArgs e)
{
    GridView1.EditIndex = e.NewEditIndex;
    BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
    GridView1.EditIndex = -1;
    BindData();
}
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
    string CustomerID = ((Label)GridView1.Rows[e.RowIndex]
                        .FindControl("lblCustomerID")).Text;
    string Name = ((TextBox)GridView1.Rows[e.RowIndex]
                        .FindControl("txtContactName")).Text;
    string Company = ((TextBox)GridView1.Rows[e.RowIndex]
                        .FindControl("txtCompany")).Text;
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "update customers set ContactName=@ContactName," +
     "CompanyName=@CompanyName where CustomerID=@CustomerID;" +
     "select CustomerID,ContactName,CompanyName from customers";
    cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID;
    cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name;
    cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company;
    GridView1.EditIndex = -1;
    GridView1.DataSource = GetData(cmd);
    GridView1.DataBind();
}



           
VB.Net

Protected Sub EditCustomer(ByVal sender As Object, ByVal e As GridViewEditEventArgs)
   GridView1.EditIndex = e.NewEditIndex
   BindData()
End Sub
Protected Sub CancelEdit(ByVal sender As Object, ByVal e As GridViewCancelEditEventArgs)
   GridView1.EditIndex = -1
   BindData()
End Sub
Protected Sub UpdateCustomer(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
   Dim CustomerID As String = DirectCast(GridView1.Rows(e.RowIndex) _
                                .FindControl("lblCustomerID"), Label).Text
   Dim Name As String = DirectCast(GridView1.Rows(e.RowIndex) _
                                .FindControl("txtContactName"), TextBox).Text
   Dim Company As String = DirectCast(GridView1.Rows(e.RowIndex) _
                                .FindControl("txtCompany"), TextBox).Text
   Dim con As New SqlConnection(strConnString)
   Dim cmd As New SqlCommand()
   cmd.CommandType = CommandType.Text
   cmd.CommandText = "update customers set ContactName=@ContactName," _
   & "CompanyName=@CompanyName where CustomerID=@CustomerID;" _
   & "select CustomerID,ContactName,CompanyName from customers"
   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value = CustomerID
   cmd.Parameters.Add("@ContactName", SqlDbType.VarChar).Value = Name
   cmd.Parameters.Add("@CompanyName", SqlDbType.VarChar).Value = Company
   GridView1.EditIndex = -1
   GridView1.DataSource = GetData(cmd)
   GridView1.DataBind()
End Sub



You can view above I am simply getting the data from the textboxes in the Footer Row and then firing an update query along with the select query so that the ASP.Net GridView control is also updated. The figure below displays the Edit and Update functionality.


Deleting existing record with Confirmation

As said above I am using custom delete button instead of ASP.Net GridView delete command field and the main reason for that is to add a confirmation.



      
C#

protected void DeleteCustomer(object sender, EventArgs e)
{
    LinkButton lnkRemove = (LinkButton)sender;
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = "delete from  customers where " +
    "CustomerID=@CustomerID;" +
     "select CustomerID,ContactName,CompanyName from customers";
    cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value
        = lnkRemove.CommandArgument;
    GridView1.DataSource = GetData(cmd);
    GridView1.DataBind();
}



VB.Net

Protected Sub DeleteCustomer(ByVal sender As Object, ByVal e As EventArgs)
   Dim lnkRemove As LinkButton = DirectCast(sender, LinkButton)
   Dim con As New SqlConnection(strConnString)
   Dim cmd As New SqlCommand()
   cmd.CommandType = CommandType.Text
   cmd.CommandText = "delete from customers where " & _
   "CustomerID=@CustomerID;" & _
   "select CustomerID,ContactName,CompanyName from customers"
   cmd.Parameters.Add("@CustomerID", SqlDbType.VarChar).Value _
       = lnkRemove.CommandArgument
   GridView1.DataSource = GetData(cmd)
   GridView1.DataBind()
End Sub



Based on the sender argument I am getting the reference of the LinkButton that is clicked and with the CommandArgument of the LinkButton I am getting the ID of the record to be deleted. After the delete query I am firing a select query and the rebinding the GridView.



Pagination

For pagination I have added the OnPageIndexChanging event on which I am assigning the new page index to the ASP.Net GridView control and then rebinding the data.

      


C#


protected void OnPaging(object sender, GridViewPageEventArgs e)
{
    BindData();
    GridView1.PageIndex = e.NewPageIndex;
    GridView1.DataBind();
}



VB.Net

Protected Sub OnPaging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
   BindData()
   GridView1.PageIndex = e.NewPageIndex
   GridView1.DataBind()
End Sub



ASP.Net AJAX and JQuery

As you have seen in the start I had added an Update Panel and a DIV along with ASP.Net GridView Control.

Basically the Update Panel will give the asynchronous calls thus not reloading the complete page and the JQuery will block the UI until the update panel is refreshed completely. But instead of blocking the complete page I am blocking only the contents of the DIV dvGrid. To achieve this I am using the JQuery BlockUI Plugin

<script type = "text/javascript" src = "scripts/jquery-1.3.2.min.js">script>
<script type = "text/javascript" src = "scripts/jquery.blockUI.js">script>
<script type = "text/javascript">
    function BlockUI(elementID) {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_beginRequest(function() {
    $("#" + elementID).block({ message: '<img src="images/loadingAnim.gif" />'
     ,css: {},
     overlayCSS: {backgroundColor:'#000000',opacity: 0.6, border:'3px solid #63B2EB'
    }
    });
    });
    prm.add_endRequest(function() {
        $("#" + elementID).unblock();
    });
    }
    $(document).ready(function() {

            BlockUI("dvGrid");
            $.blockUI.defaults.css = {};           
    });
script>


That’s all the scripting required and the following is achieved with the above scripts. It will block the Grid until the update panel finishes its work. Refer the figure below



That’s it. With this the article comes to an end, hope you liked it I’ll get back soon with a new one.