Pages

28 Aug 2013

ADO.NET Interview Question - Asp.net C#, VB.net

Which architecture does Datasets follow?

Datasets follow the disconnected data architecture.

16. What is the role of the DataSet object in ADO.NET?

One of the major component of ADO.NET is the DataSet object, which always remains disconnected from the database and reduces the load on the database.

What is a DataReader object?

The DataReader object helps in retrieving the data from a database in a forward-only, read-only mode. The base class for all the DataReader objects is the DbDataReader class.

The DataReader object is returned as a result of calling the ExecuteReader() method of the Command object. The DataReader object enables faster retrieval of data from databases and enhances the performance of .NET applications by providing rapid data access speed. However, it is less preferred as compared to the DataAdapter object because the DataReader object needs an Open connection till it completes reading all the rows of the specified table.

An Open connection to read data from large tables consumes most of the system resources. When multiple client applications simultaneously access a database by using the DataReader object, the performance of data retrieval and other related processes is substantially reduced. In such a case, the database might refuse connections to other .NET applications until other clients free the resources.

How can you identify whether or not any changes are made to the DataSet object since it was last loaded?

The DataSet object provides the following two methods to track down the changes:
The GetChanges() method - Returns the DataSet object, which is changed since it was loaded or since the AcceptChanges() method was executed.
The HasChanges() method - Indicates if any changes occurred since the DataSet object was loaded or after a call to the AcceptChanges() method was made.

Mention different types of data providers available in .NET Framework. - Interview Question

.NET Framework Data Provider for SQL Server - Provides access to Microsoft SQL Server 7.0 or later version. It uses the System.Data.SqlClient namespace.
.NET Framework Data Provider for OLE DB - Provides access to databases exposed by using OLE DB. It uses the System.Data.OleDb namespace.
.NET Framework Data Provider for ODBC - Provides access to databases exposed by using ODBC. It uses the System.Data.Odbc namespace.
.NET Framework Data Provider for Oracle - Provides access to Oracle database 8.1.7 or later versions. It uses the System.Data.OracleClient namespace.

Name the two properties of the GridView control that have to be specified to turn on sorting and paging.

The properties of the GridView control that need to be specified to turn on sorting and paging are as follows:
The AllowSorting property of the Gridview control indicates whether sorting is enabled or not. You should set the AllowSorting property to True to enable sorting.
The AllowPaging property of the Gridview control indicates whether paging is enabled or not. You should set the AllowPaging property to True to enable paging.

Asp.net interview questions on gridview C#, vb.net

What is DataGrid...

We can define DataGrid as a Powerfull WebServer tool which is used for displaying information from a DataSource in a tabular form an enables us to perform Sorting, Paging and Editing by setting a few properties and creating a couple of event handlers.

How Web DataGrid is Different from Windows DataGrid Control...

The WebPage DataGrid control is Different from Windows DataGrid in entire programming paradigm. Let's see...

* Web DataGrid Control performs a round trip to the server.
* Web DataGrid manage State.
* Windows DataGrid Control Supports master-detail data structure while web Datagrid doesn't.
* In Web DataGrid ,you can Edit only one row at a time.
* Web DataGrid Does not inherently support sorting, but raises events while Windows DataGrid does support.
* Web DataGrid supports Paging.
* You can bind Web DataGrid Control to any object that supports the IEnumerable interface.

How do you bind data in the DataGrid?

Binding Data in DataGrid means how we show the data from a table or a relation in our DataGrid.

Suppose We want to show the data of "Customers" table of "Northwind" database present in SQL Server on the Button Click. Now Follow the given steps....

step 1: Drag a DataGrid and a Button control on the Page.
step 2: In the Code behind Use the namespace as
using System.Data.SqlClient;
step 3: Write the following code in the Button's Click event handler...

protected void Button1_Click(object sender,EventArgs e)
{
SqlConnection con=new SqlConnection ("server=rajkumar;uid=sa;pwd=kumar;database=northwind) ;
SqlDataAdapter da_show=new SqlDataAdapter (" select ProductName, UnitPrice, UnitsInStock from Products", con);
DataSet ds=new DataSet;
da_show.Fill(ds, "Products");
GridView1.DataSource=ds.Tables["products"];
GridView1.DataBind( );
}

This will show all the rows and selected column in the DataGrid. The Column names in the DataGrid will be same as attributes name in the database table.

How do you customize the DataGrid...

Here I will show you how to Display only Selected Column in the DataGrid even when you selected all the columns in your Query in Code Behind file. Also I will show you how to change the Name of the Column in the DataGrid.

Suppose I want to Display only ProductName and UnitPrice from the table and Also Want To display ProductName as Product Name and UnitPrice as Price......So

Step 1 : In the Code behind file the code will be same as above.
Step 2 : Set the Property AutoGenerateColumns of DataGrid to false.
Step 3 : Go to source View and Insert TemplateColumns in the datagrid tag.

DOT NET/ASP.NET interview questions: - When to consider Data grid, data list, or repeater?

This is one of quiet often asked .NET/ASP.NET interview questions so prepare accordingly to answer it to the interviewer.

Many of the developers make a blind choice of choosing data grid directly, but that is not the right way.

Data grid provides ability to allow the end-user to sort, page, and edit its data. However, it comes at a cost of speed. Second, the display format is simple that is in row and columns. Real life scenarios can be more demanding that

With its templates, the Data List provides more control over the look and feel of the displayed data than the Data Grid. It offers better performance than data grid

Repeater control allows for complete and total control. With the Repeater, the only HTML emitted are the values of the data binding statements in the templates along with the HTML markup specified in the templates no "extra" HTML is emitted, as with the Data Grid and Data List. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. However, repeater does not provide editing features like data grid so everything has to be coded by programmer. However, the Repeater does boast the best performance of the three data Web controls. Repeater is fastest followed by Datalist and finally data grid.

See video on ASP.NET 4.0 web.config transformation as follows: -


Reading HTML Data from any website

Hi,

This is how I solved the problem of extracting info from a html table.
Means, The site which have data in a tabular or list format, then you can read data by using HTMLAgility Pack.


Download HTMLAgilityPack.dll and add referce to it in your project.



Sample code are written as:-

HTML
<BODY>
<TABLE>
<TR>
<TD>Row 0, Col 0</TD>
<TD>Row 0, Col 1</TD>
</TR>
<TR>
<TD>Row 1, Col 0</TD>
<TD>Row 1, Col 1<TD>
</TR>
</TABLE>
</BODY>

Code
// Load the html document
HtmlWeb web = new HtmlWeb();
HtmlDocument doc = web.Load("http://myServer/myTable.htm");

// Get all tables in the document
HtmlNodeCollection tables = doc.DocumentNode.SelectNodes("//TABLE");

// Iterate all rows in the first table
HtmlNodeCollection rows = tables[0].SelectNodes(".//TR");
for (int i = 0; i < rows.Count; ++i) {

// Iterate all columns in this row
HtmlNodeCollections cols = rows[i].SelectNodes(".//TD");
for (int j = 0; j < cols.Count; ++j) {

// Get the value of the column and print it
string value = cols[j].InnerText;
Console.WriteLine(value);
}
}

Result
Row 0, Col 0
Row 0, Col 1
Row 1, Col 0
Row 1, Col 1

27 Aug 2013

jQuery.each() JSON Example using Jquery

(function($) {
var json = [
    { "red": "#f00" },
    { "green": "#0f0" },
    { "blue": "#00f" }
];

$.each(json, function() {
  $.each(this, function(name, value) {
    /// do stuff
    console.log(name + '=' + value);
  });
});
//outputs: red=#f00 green=#0f0 blue=#00f
})(jQuery);

jQuery.each() Class Example using Jquery

This example shows you how to loop through each element with class=”productDesc” given in the HTML below.


<div class=”productDesc” >Red</div>
<div class=”productDesc” >Orange</div>
<div class=”productDesc” >Green</div>


$.each($('.productDesc'), function(index, value) { 
    console.log(index + ':' + value); 
});
//outputs: 1:Red 2:Orange 3:Green


You don’t have to include index and value these are just parameters which help determine which DOM element your currently iterating. You could also write it like this:

$.each($('.productDesc'), function() { 
    console.log($(this).html());
});
//outputs: Red Orange Green

26 Aug 2013

jQuery.each() Array Example with Jquery

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value);
});
//outputs: 1:1 2:2 3:3 4:4 5:5

Basic jQuery.each() Function Example using JQuery


$('a').each(function(index, value){
      console.log($(this).attr('href'));
});
//outputs: every links href element on your web page

$('a').each(function(index, value){
    var ihref = $(this).attr('href');
    if (ihref.indexOf("http") >= 0)
    {
        console.log(ihref+'<br/>');
    }
});
//outputs: every external href on your web page

jQuery .each() Syntax using JQuery

//DOM ELEMENTS $("div").each(function(index, value) { console.log('div' + index + ':' + $(this).attr('id')); }); //outputs the ids of every div on the web page //ie - div1:header, div2:body, div3:footer //ARRAYS var arr = [ "one", "two", "three", "four", "five" ]; jQuery.each(arr, function(index, value) { console.log(this); return (this != "three"); // will stop running after "three" }); //outputs: one two three //OBJECTS var obj = { one:1, two:2, three:3, four:4, five:5 }; jQuery.each(obj, function(i, val) { console.log(val); }); //outputs: 1 2 3 4 5

getElementById OR get textbox Elements id on forms with using javascript

Method 1: Using an ID
Code:
function add(text){
    var TheTextBox = document.getElementById("Mytextbox");
    TheTextBox.value = TheTextBox.value + text;
}



Method 2: using the form:
Code:
function add(text){
    var TheTextBox = document.forms[0].elements['field_name']; //I think that's right, haven't done it in a while
    TheTextBox.value = TheTextBox.value + text;
}

Using dateadd in SQL Server to add intervals to dates

The syntax for the dateadd() function in SQL Server is as follows:

DATEADD (datepart, number, date)
"datepart" is the interval type you wish to add or subtract for example day, month, year, hour, minute, second. These can be abbreviated as dd and d for day, mm and m for month, yy and yyyy for year, hh for hour, mi and n for minute and ss and s for second.

The number is the amount of datepart units to add or subtract. For example if datepart was d and the number was 3 then it would add three days to the date specified.

And finally, date is the date to add/subtract the number of dateparts from. It can either be a column in the database, a constant value or a function such as GETDATE() which would return the current date and time.

Using the same examples from the MySQL post, to show the current date and time, and to add a month to the current date you would do this:

SELECT GETDATE(), DATEADD(month, 1, GETDATE())
which would give you the following result:

2008-10-03 14:57:09.907
2008-11-03 14:57:09.907
To subtract a month to the current, simply make a negative number value:

SELECT GETDATE(), DATEADD(month, -1, GETDATE())
which would give the following result:

2008-10-03 14:58:08.113
2008-09-03 14:58:08.113
And to use the same example from the MySQL article, if we have a table called "products" and it has a column called "backorder_date" which has a column type of date, we could run this query to add three days onto the back order date which is the value we might display on a website:

SELECT DATEADD(day, 3, backorder_date) AS backorder_date FROM products
and an example result

2008-10-18 00:00:00.000
It's very easy to add and subtract dates using Microsoft SQL Server. The are often circumstances when you would need to use this and do it in the database rather than in business logic or website code, such as calculating the backorder date of a product in the last example above.

23 Aug 2013

Contact Form For Mail Code in PHP through using MSN SMTP

Contact Form For Mail Code in PHP through using MSN SMTP

<?php
require_once('mail/class.phpmailer.php'); // download php mailer class

$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$contact = $_POST['contact']; // not required
$email = $_POST['email']; // not required
$address = $_POST['address']; // not required
$pcode = $_POST['code']; // not required
$price = $_POST['price']; // required
$qty = $_POST['qty']; // required
$comments = $_POST['comments']; // required



$strmsg=("<p>Hi, </p><p>Name: $fname $lname </p><p>Contact: $contact </p><p>Email -Id: $email </p><p>Address: $address </p><p>Product Code No.: $pcode </p><p>Price: $price </p><p>Quantity: $qty </p></br>Comments : $comments");

//echo($strmsg);

$mail = new PHPMailer();
$mail->IsSMTP();
$mail->CharSet="UTF-8";
$mail->SMTPSecure = 'tls';
$mail->Host = 'smtp.live.com';
$mail->Port = 587;
$mail->Username = 'frommailid';
$mail->Password = 'password';
$mail->SMTPAuth = true;

$mail->From = 'frommailid';
$mail->FromName = 'name';
$mail->AddAddress('emailid');
$mail->AddReplyTo('fromemilid', 'Information');

$mail->IsHTML(true);
$mail->Subject    = "subject";
//$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!";
$mail->Body    = $strmsg;

if(!$mail->Send())
{
  echo "Mailer Error: " . $mail->ErrorInfo;
}
else
{
  echo "Your message was successfully sent! Thank you for contacting us, we will reply to your inquiry as soon as possible!";
}
?>

22 Aug 2013

Get Browsers Parameter Value From URL With Javascript Code, Asp.net HTML and PHP

function getURLParameters()
{
var sURL = window.document.URL.toString();

if (sURL.indexOf("?") > 0)
{
var arrParams = sURL.split("?");

var arrURLParams = arrParams[1].split("&");

var arrParamNames = new Array(arrURLParams.length);
var arrParamValues = new Array(arrURLParams.length);

var i = 0;
for (i=0;i<arrURLParams.length;i++)
{
var sParam =  arrURLParams[i].split("=");
arrParamNames[i] = sParam[0];
if (sParam[1] != "")
arrParamValues[i] = unescape(sParam[1]);
else
arrParamValues[i] = "No Value";
}

for (i=0;i<arrURLParams.length;i++)
{
alert(arrParamNames[i]+" = "+ arrParamValues[i]);
}
}
else
{
alert("No parameters.");
}
}

<body onload=" getURLParameters() ">

SQL SERVER – Get Date Time in Any Format

Refer the function and get familiar yourself with different format this function support. I have added few examples of how this function can be used at the end of the article


CREATE FUNCTION [dbo].[ufsFormat]
(
@Date datetime,
@fORMAT VARCHAR(80)
)
RETURNS NVARCHAR(80)
AS
BEGIN
DECLARE @Dateformat INT
DECLARE @ReturnedDate VARCHAR(80)
DECLARE @TwelveHourClock INT
DECLARE @Before INT
DECLARE @pos INT
DECLARE @Escape INT
-- (c) Pinal Dave http://www.SQLAuthority.com
SELECT @ReturnedDate='error! unrecognised format '+@format
SELECT @DateFormat=CASE @format
WHEN 'mmm dd yyyy hh:mm AM/PM' THEN 100
WHEN 'mm/dd/yy' THEN 1
WHEN 'mm/dd/yyyy' THEN 101
WHEN 'yy.mm.dd' THEN 2
WHEN 'dd/mm/yy' THEN 3
WHEN 'dd.mm.yy' THEN 4
WHEN 'dd-mm-yy' THEN 5
WHEN 'dd Mmm yy' THEN 6
WHEN 'Mmm dd, yy' THEN 7
WHEN 'hh:mm:ss' THEN 8
WHEN 'yyyy.mm.dd' THEN 102
WHEN 'dd/mm/yyyy' THEN 103
WHEN 'dd.mm.yyyy' THEN 104
WHEN 'dd-mm-yyyy' THEN 105
WHEN 'dd Mmm yyyy' THEN 106
WHEN 'Mmm dd, yyyy' THEN 107
WHEN 'Mmm dd yyyy hh:mm:ss:ms AM/PM' THEN 9
WHEN 'Mmm dd yyyy hh:mi:ss:mmm AM/PM' THEN 9
WHEN 'Mmm dd yy hh:mm:ss:ms AM/PM' THEN 109
WHEN 'mm-dd-yy' THEN 10
WHEN 'mm-dd-yyyy' THEN 110
WHEN 'yy/mm/dd' THEN 11
WHEN 'yyyy/mm/dd' THEN 111
WHEN 'yymmdd' THEN 12
WHEN 'yyyymmdd' THEN 112
WHEN 'dd Mmm yyyy hh:mm:ss:Ms' THEN 113
WHEN 'hh:mm:ss:Ms' THEN 14
WHEN 'yyyy-mm-dd hh:mm:ss' THEN 120
WHEN 'yyyy-mm-dd hh:mm:ss.Ms' THEN 121
WHEN 'yyyy-mm-ddThh:mm:ss.Ms' THEN 126
WHEN 'dd Mmm yyyy hh:mm:ss:ms AM/PM' THEN 130
WHEN 'dd/mm/yy hh:mm:ss:ms AM/PM' THEN 131
WHEN 'RFC822' THEN 2
WHEN 'dd Mmm yyyy hh:mm' THEN 4
ELSE 1 END
SELECT @ReturnedDate='error! unrecognised format ' +@format+CONVERT(VARCHAR(10),@DateFormat)
IF @DateFormat>=0
SELECT @ReturnedDate=CONVERT(VARCHAR(80),@Date,@DateFormat)
--check for favourite and custom formats that can be done quickly
ELSE IF @DateFormat=-2--then it is RFC822 format
SELECT @ReturnedDate=LEFT(DATENAME(dw, @Date),3) + ', ' + STUFF(CONVERT(NVARCHAR,@Date,113),21,4,' GMT')
ELSE IF @DateFormat=-4--then it is european day format with minutes
SELECT @ReturnedDate=CONVERT(CHAR(17),@Date,113)
ELSE
BEGIN
SELECT @Before=LEN(@format)
SELECT @Format=REPLACE(REPLACE(REPLACE( @Format,'AM/PM','#'),'AM','#'),'PM','#')
SELECT @TwelveHourClock=CASE WHEN @Before >LEN(@format) THEN 109 ELSE 113 END, @ReturnedDate=''
WHILE (1=1)--forever
BEGIN
SELECT @pos=PATINDEX('%[yqmidwhs:#]%',@format+' ')
IF @pos=0--no more date format strings
BEGIN
SELECT @ReturnedDate=@ReturnedDate+@format
BREAK
END
IF @pos>1--some stuff to pass through first
BEGIN
SELECT @escape=CHARINDEX ('\',@Format+'\') --is it a literal character that is escaped?
IF @escape<@pos BEGIN
SET @ReturnedDate=@ReturnedDate+SUBSTRING(@Format,1,@escape-1) +SUBSTRING(@format,@escape+1,1)
SET @format=RTRIM(SUBSTRING(@Format,@Escape+2,80))
CONTINUE
END
SET @ReturnedDate=@ReturnedDate+SUBSTRING(@Format,1,@pos-1)
SET @format=RTRIM(SUBSTRING(@Format,@pos,80))
END
SELECT @pos=PATINDEX('%[^yqmidwhs:#]%',@format+' ')--get the end
SELECT @ReturnedDate=@ReturnedDate+--'('+substring(@Format,1,@pos-1)+')'+
CASE SUBSTRING(@Format,1,@pos-1)
--Mmmths as 1--12
WHEN 'M' THEN CONVERT(VARCHAR(2),DATEPART(MONTH,@Date))
--Mmmths as 01--12
WHEN 'Mm' THEN CONVERT(CHAR(2),@Date,101)
--Mmmths as Jan--Dec
WHEN 'Mmm' THEN CONVERT(CHAR(3),DATENAME(MONTH,@Date))
--Mmmths as January--December
WHEN 'Mmmm' THEN DATENAME(MONTH,@Date)
--Mmmths as the first letter of the Mmmth
WHEN 'Mmmmm' THEN CONVERT(CHAR(1),DATENAME(MONTH,@Date))
--Days as 1--31
WHEN 'D' THEN CONVERT(VARCHAR(2),DATEPART(DAY,@Date))
--Days as 01--31
WHEN 'Dd' THEN CONVERT(CHAR(2),@date,103)
--Days as Sun--Sat
WHEN 'Ddd' THEN CONVERT(CHAR(3),DATENAME(weekday,@Date))
--Days as Sunday--Saturday
WHEN 'Dddd' THEN DATENAME(weekday,@Date)
--Years as 00--99
WHEN 'Yy' THEN CONVERT(CHAR(2),@Date,12)
--Years as 1900--9999
WHEN 'Yyyy' THEN DATENAME(YEAR,@Date)
WHEN 'hh:mm:ss' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,8)
WHEN 'hh:mm:ss:ms' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'h:mm:ss' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,8)
--tthe SQL Server BOL syntax, for compatibility
WHEN 'hh:mi:ss:mmm' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'h:mm:ss:ms' THEN SUBSTRING(CONVERT(CHAR(30),@date,@TwelveHourClock),13,12)
WHEN 'H:m:s' THEN SUBSTRING(REPLACE(':'+SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,8),':0',':'),2,30)
WHEN 'H:m:s:ms' THEN SUBSTRING(REPLACE(':'+SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,12),':0',':'),2,30)
--Hours as 00--23
WHEN 'hh' THEN REPLACE(SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,2),' ','0')
--Hours as 0--23
WHEN 'h' THEN LTRIM(SUBSTRING(CONVERT(CHAR(30), @Date,@TwelveHourClock),13,2))
--Minutes as 00--59
WHEN 'Mi' THEN DATENAME(minute,@date)
WHEN 'mm' THEN DATENAME(minute,@date)
WHEN 'm' THEN CONVERT(VARCHAR(2),DATEPART(minute,@date))
--Seconds as 0--59
WHEN 'ss' THEN DATENAME(second,@date)
--Seconds as 0--59
WHEN 'S' THEN CONVERT(VARCHAR(2),DATEPART(second,@date))
--AM/PM
WHEN 'ms' THEN DATENAME(millisecond,@date)
WHEN 'mmm' THEN DATENAME(millisecond,@date)
WHEN 'dy' THEN DATENAME(dy,@date)
WHEN 'qq' THEN DATENAME(qq,@date)
WHEN 'ww' THEN DATENAME(ww,@date)
WHEN '#' THEN REVERSE(SUBSTRING(REVERSE(CONVERT(CHAR(26), @date,109)),1,2))
ELSE
SUBSTRING(@Format,1,@pos-1)
END
SET @format=RTRIM(SUBSTRING(@Format,@pos,80))
END
END
RETURN @ReturnedDate
END
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'mm/dd/yy')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'hh:mm:ss')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'mmm')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', 'Mmm dd yyyy hh:mm:ss:ms AM/PM')
GO
SELECT [dbo].[ufsFormat] ('8/7/2008', '#')
GO

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.