Pages

Friday 28 February 2014

How to setTimeout Function Example JavaScript c#

How to setTimeout Function Example JavaScript c#

Method 1:
 
 setTimeout(yourfunction(), timeinterval);

function yourfunction() {
// your code here
}

Method 2:

 setTimeout(function(){// your code here
}, timeinterval);

Sample Code:

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript display current time on webpage</title>
<script type="text/javascript">
    function ShowCurrentTime() {
        var dt = new Date();
        document.getElementById("lblTime").innerHTML = dt.toLocaleTimeString();
        setTimeout("ShowCurrentTime()", 1000); // Here 1000(milliseconds) means one 1 Sec
    }
</script>
</head>
<body onload="ShowCurrentTime()">
<div>
JavaScript Display current time second by second:
<label id="lblTime" style=" font-weight:bold"></label>
</div>
</body>
</html>

Live Demo:

JavaScript display current time on webpage
JavaScript Display current time second by second:


Thursday 27 February 2014

How to Get Query String Parameter Values with Spaces in C#

How to Get Query String Parameter Values with Spaces in C#

we have to use decodeURIComponent JavaScript function in our code.

 <script type="text/javascript">
     $(function () {
         var str = decodeURIComponent('Welcome%20To%20http%3A%2f%2ffantasyaspnet.blogspot.in%2f')
         alert(str);
     })
</script>

Example:

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to Get Query String Parameter Values with Spaces in C#</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        var name = GetParameterValues('username');
        var id = GetParameterValues('name');
        $('#spn_UserName').html('<strong>' + name + '</strong>');
        $('#spn_UserId').html('<strong>' + id + '</strong>');
    });
    function GetParameterValues(param) {
        var url = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < url.length; i++) {
            var urlparam = url[i].split('=');
            if (urlparam[0] == param) {
                return decodeURIComponent(urlparam[1]);
            }
        }
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>UserName: <span id="spn_UserName"></span></p>
<p>Name: <span id="spn_UserId"></span></p>
</div>
</form>
</body>
</html>

Demo: 


Using Statement Example OR Uses of Using Statement in C#

Using Statement Example OR Uses of Using Statement in C#
 
If we use using statement in our applications it will automatically create try / finally blocks for the objects and automatically runs Dispose() method for us no need to create any try/finally block and no need to run any Dispose() method.

C#
 
 using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand (commandString, con))
{
con.Open();
cmd.ExecuteNonQuery();
}
}

VB

Using con As New SqlConnection(connectionString)
Using cmd As New SqlCommand(commandString, con)
con.Open()
cmd.ExecuteNonQuery()
End Using
End Using

Add/Copy Rows from One Datatable to Another Datatable C#

Add/Copy Rows from One Datatable to Another Datatable C#

C# 
 
DataTable _dt=new DataTable();
_dt = _ds.Tables[0];
DataTable dt1 = ds1.Tables[0];
for (int i = 0; i < dt1.Rows.Count; i++)
{
_dt.ImportRow(dt1.Rows[i]);
}

VB

Dim _dt As New DataTable()
_dt = _ds.Tables(0)
Dim dt1 As DataTable = ds1.Tables(0)
For i As Integer = 0 To dt1.Rows.Count - 1
_dt.ImportRow(dt1.Rows(i))
Next


Difference between View and Stored Procedure

Difference between View and Stored Procedure

 View in SQL Server

A view represents a virtual table. By using view we can join multiple tables and present the data as coming from a single table.

For example consider we have two tables

      1)    UserInformation table with columns userid, username
      2)    SalaryInformation table with columns salid, userid, salary

Create VIEW by joining above two tables 
 
CREATE VIEW VW_UserInfo
AS
BEGIN
SELECT a.userid,a.username,b.salary from UserInformation a INNER JOIN SalaryInformation b ON a.userid=b.userid
END

 CREATE PROCEDURE GetUserInfo
@uid INT
AS
BEGIN
SELECT username from VW_UserInfo WHERE userid=@uid
END

Stored Procedure

 A stored procedure is a group of sql statements that has been created and stored in the database. Stored procedure will accept input parameters so that a single procedure can be used over the network by several clients using different input data. Stored procedure will reduce network traffic and increase the performance. If we modify stored procedure all the clients will get the updated stored procedure

 USE AdventureWorks2008R2;
GO
CREATE PROCEDURE dbo.sp_who
AS
    SELECT FirstName, LastName FROM Person.Person;
GO
EXEC sp_who;
EXEC dbo.sp_who;
GO
DROP PROCEDURE dbo.sp_who;
GO

Wednesday 26 February 2014

How to use Wiki Plugin to Show Wikipedia Description in Tooltips Using Jquery

How to use Wiki Plugin to Show Wikipedia Description in Tooltips Using Jquery

.Aspx Page 
 
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery plugin to show wikipedia description in tooltips</title>
<link href="wikiUp.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="wikiUp.js" type="text/javascript"></script>
</head>
<body>
<data data-wiki="Apple Inc."><b>Apple</b></data> was founded by <data data-wiki="Steve Jobs"><b>Steve Jobs</b></data>.
<data data-wiki="Madrid" data-lang="es"><b>Madrid</b></data> es la capital de España.
</body>
</html>

We have to add files “wikiUp.css” and “wikiUp.js” in our aspx file.You can download from hear
Demo:




What is Delegates in C# Example | Use of Delegates in C#

What is Delegates in C# Example | Use of Delegates in C# 

 In Simple Language A delegate is an object that can refer to a method. Thus, when you create a delegate, you are creating an object that can hold a reference to a method.

Syntax of Delegate & Methods Declaration

 public delegate int Delegatmethod(int a,int b);

public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
}
}

Example:

 public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();

DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}

Output:

Add Result : 30
Sub Result : 10

Delegates are two types
  •       Single Cast Delegates
  • Multi Cast Delegates
Syntax of Multicast Delegate & Method Declaration

  public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}

Example

 public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}

Output:

Addition Value : 15
Subtraction Value : 5
Multiply Value : 50


Output Console Window Closing Automatically without Showing Output in c#

Output Console Window Closing Automatically without Showing Output  c#

 we just need to add Console.ReadLine()at the end of your code.Below is the example

 class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to http://fantasyaspnet.blogspot.in/");
Console.ReadLine();
}
}


Difference between Virtual Override New Keywords with Example c#

Difference between Virtual Override New Keywords with Example c#

Generally virtual and override keywords will occur in overriding method of polymorphism concept and new keyword will be used to hide the method. Here I will explain these keywords with example for that check below code. I have one method Show() which exists in two classes SampleA and SampleB as shown below

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public void Show()
{
Console.WriteLine("Sample B Test Method");
}
}

class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample A Test Method

New Keyword Example or Method Hiding

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Virtual and Override Keywords Example or Method Overriding:


using System;
namespace ConsoleApplication3
{
class SampleA
{
public virtual void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public override void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
a.Show();
b.Show();
a = new SampleB();
a.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample B Test Method

Use Both Method Overriding & Method Hiding:

 using System;
namespace ConsoleApplication3
{
class SampleA
{
public void Show()
{
Console.WriteLine("Sample A Test Method");
}
}
class SampleB:SampleA
{
public new virtual void Show()
{
Console.WriteLine("Sample B Test Method");
}
}
class SampleC : SampleB
{
public override void Show()
{
Console.WriteLine("Sample C Test Method");
}
}
class Program
{
static void Main(string[] args)
{
SampleA a=new SampleA();
SampleB b=new SampleB();
SampleB c = new SampleC();
a.Show();
b.Show();
c.Show();
a = new SampleB();
a.Show();
b = new SampleC();
b.Show();
Console.ReadLine();
}
}
}

Output:

Sample A Test Method
Sample B Test Method
Sample C Test Method
Sample A Test Method
Sample C Test Method



How to Select Deselect All Check boxes with Name Using jquery in c#

How to Select Deselect All Check boxes with Name Using jquery in c#
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Select Deselect all Checkboxes</title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('input[name="chkUser"]').click(function () {
            if ($('input[name="chkUser"]').length == $('input[name="chkUser"]:checked').length) {
                $('input:checkbox[name="chkAll"]').attr("checked", "checked");
            }
            else {
                $('input:checkbox[name="chkAll"]').removeAttr("checked");
            }
        });
        $('input:checkbox[name="chkAll"]').click(function () {
            var slvals = []
            if ($(this).is(':checked')) {
                $('input[name="chkUser"]').attr("checked", true);
            }
            else {
                $('input[name="chkUser"]').attr("checked", false);
                slvals = null;
            }
        });
    })
</script>
<style type="text/css">
li
{
list-style-type:none;
}
</style></head>
<body>
<ul>
<li><label><input type="checkbox" name="chkAll" value="All"/>
Select All
</label></li>
<li><label><input type="checkbox" name="chkUser" value="3930"/>sizar</label></li>
<li><label><input type="checkbox" name="chkUser" value="4049"/>sahil</label></li>
<li><label><input type="checkbox" name="chkUser" value="4076"/>salim</label></li>
<li><label><input type="checkbox" name="chkUser" value="4086"/>rameez</label></li>
<li><label><input type="checkbox" name="chkUser" value="4087"/>nasir</label></li>
<li><label><input type="checkbox" name="chkUser" value="4116"/>karim</label></li>

</ul>
</body>
</html>

Demo:




How to Check Unchecked All Check boxes with Header in using jQuery c#

How to Check Unchecked All Check boxes with Header in using jQuery c#

.Aspx:
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Check uncheck all Checkboxes</title>
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $('input[name="chkUser"]').click(function () {
            if ($('input[name="chkUser"]').length == $('input[name="chkUser"]:checked').length) {
                $('input:checkbox[name="chkAll"]').attr("checked", "checked");
            }
            else {
                $('input:checkbox[name="chkAll"]').removeAttr("checked");
            }
        });
        $('input:checkbox[name="chkAll"]').click(function () {
            var slvals = []
            if ($(this).is(':checked')) {
                $('input[name="chkUser"]').attr("checked", true);
            }
            else {
                $('input[name="chkUser"]').attr("checked", false);
                slvals = null;
            }
        });
    })
</script>
<style type="text/css">
li
{
list-style-type:none;
}
</style></head>
<body>
<ul>
<li><label><input type="checkbox" name="chkAll" value="All"/>
Select All
</label></li>
<li><label><input type="checkbox" name="chkUser" value="3930"/>sizar</label></li>
<li><label><input type="checkbox" name="chkUser" value="4049"/>sahil</label></li>
<li><label><input type="checkbox" name="chkUser" value="4076"/>salim</label></li>
<li><label><input type="checkbox" name="chkUser" value="4086"/>rameez</label></li>
<li><label><input type="checkbox" name="chkUser" value="4087"/>nasir</label></li>
<li><label><input type="checkbox" name="chkUser" value="4116"/>karim</label></li>
</ul>
</body>
</html>

Demo:
 



Constructors in C# with Example, Types of Constructor in C# with Example

Constructors in C# with Example, Types of Constructor in C# with Example

Generally constructor name should be same as class name. If we want to create constructor in a class we need to create a constructor method name same as class name check below sample method for constructor

class SampleA
{
public SampleA()
{
Console.WriteLine("Sample A Test Method");
}
}

 Types of Constructors

Basically constructors are 5 types those are

      1.    Default Constructor
      2.    Parametrized Constructor
      3.    Copy Constructor
      4.    Static Constructor
      5.    Private Constructor

1.    Default Constructor

 using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample()     // Default Constructor
{
param1 = "Welcome";
param2 = "http://fantasyaspnet.blogspot.in/";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample();   // Once object of class created automatically constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}
}

Output:


Welcome
http://fantasyaspnet.blogspot.in/

Parametrized Constructors

 using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","http://fantasyaspnet.blogspot.in/");   // Parameterized Constructor Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}
}

Output:

Welcome to http://fantasyaspnet.blogspot.in/

Constructor Overloading

 using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;

public Sample()     // Default Constructor
{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y)     // Declaring Parameterized constructor with Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample();   // Default Constructor will Called
Sample obj1=new Sample("Welcome","http://fantasyaspnet.blogspot.in/");   // Parameterized Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}

Output:
Hi, I am Default Constructor
Welcome to http://fantasyaspnet.blogspot.in/

Copy Constructor
 using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
public Sample(string x, string y)
{
param1 = x;
param2 = y;
}
public Sample(Sample obj)     // Copy Constructor
{
param1 = obj.param1;
param2 = obj.param2;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj = new Sample("Welcome", "http://fantasyaspnet.blogspot.in/");  // Create instance to class Sample
Sample obj1=new Sample(obj); // Here obj details will copied to obj1
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}
}

Output:
Welcome to http://fantasyaspnet.blogspot.in/

Static Constructor

 using System;
namespace ConsoleApplication3
{
class Sample
{
public string param1, param2;
static Sample()
{
Console.WriteLine("Static Constructor");
}
public Sample()
{
param1 = "Sample";
param2 = "Instance Constructor";
}
}
class Program
{
static void Main(string[] args)
{
// Here Both Static and instance constructors are invoked for first instance
Sample obj=new Sample();
Console.WriteLine(obj.param1 + " " + obj.param2);
// Here only instance constructor will be invoked
Sample obj1 = new Sample();
Console.WriteLine(obj1.param1 +" " + obj1.param2);
Console.ReadLine();
}
}
}

Output:

Static Constructor
Sample Instance Constructor
Sample Instance Constructor

Private Constructor
 using System;
namespace ConsoleApplication3
{
public class Sample
{
public string param1, param2;
public Sample(string a,string b)
{
param1 = a;
param2 = b;
}
private Sample()  // Private Constructor Declaration
{
Console.WriteLine("Private Constructor with no prameters");
}
}
class Program
{
static void Main(string[] args)
{
// Here we don't have chance to create instace for private constructor
Sample obj = new Sample("Welcome","to http://fantasyaspnet.blogspot.in/");
Console.WriteLine(obj.param1 +" " + obj.param2);
Console.ReadLine();
}
}
}

Output

Welcome to http://fantasyaspnet.blogspot.in/

In above method we can create object of class with parameters will work fine. If create object of class without parameters it will not allow us create.

// it will works fine Sample obj = new Sample("Welcome","to http://fantasyaspnet.blogspot.in/");
 // it will not work because of inaccessability
 Sample obj=new Sample();


Regex to Replace All Special Characters with Space in String c#

Regex to Replace All Special Characters with Space in String c#

C#
 
 using System;
using System.Text.RegularExpressions;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string str = "http://fantasyaspnet.blogspot.in/";
string replacestr= Regex.Replace(str, "[^a-zA-Z0-9_]+", " ");
Console.WriteLine(replacestr);
Console.ReadLine();
}
}
}

VB
 
 Imports System.Text.RegularExpressions
Module Module1
Sub Main()
Dim str As String = "http://fantasyaspnet.blogspot.in/"
Dim replacestr As String = Regex.Replace(str, "[^a-zA-Z0-9_]+", " ")
Console.WriteLine(replacestr)
Console.ReadLine()
End Sub
End Module

Demo:

http fantasyaspnet blogspot in

How to Create Captcha with Refresh Button in C#, VB.NET

How to Create Captcha with Refresh Button in C#, VB.NET 

.Aspx File
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Captcha Image with Refresh Button</title>
<script type="text/javascript">
    function RefreshCaptcha() {
        var img = document.getElementById("imgCaptcha");
        img.src = "Handler.ashx?query=" + Math.random();
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="Handler.ashx" id="imgCaptcha" />
<a href="#" onclick="javascript:RefreshCaptcha();">Refresh</a>
</div>
</form>
</body>
</html>

Now Right click on website
 -> Select Add New Item
 -> Select Generic Handler file and give name as Handler.ashx and click ok

open Handler.ashx
 
c#

 <%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Web;

public class Handler : IHttpHandler {

public void ProcessRequest (HttpContext context) {
using (Bitmap b = new Bitmap(150, 40, PixelFormat.Format32bppArgb))
{
using (Graphics g = Graphics.FromImage(b))
{
Rectangle rect = new Rectangle(0, 0, 149, 39);
g.FillRectangle(Brushes.White, rect);

// Create string to draw.
Random r = new Random();
int startIndex = r.Next(1, 5);
int length = r.Next(5, 10);
String drawString = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length);

// Create font and brush.
Font drawFont = new Font("Arial", 16, FontStyle.Italic | FontStyle.Strikeout);
using (SolidBrush drawBrush = new SolidBrush(Color.Black))
{
// Create point for upper-left corner of drawing.
PointF drawPoint = new PointF(15, 10);

// Draw string to screen.
g.DrawRectangle(new Pen(Color.Red, 0), rect);
g.DrawString(drawString, drawFont, drawBrush, drawPoint);
}
b.Save(context.Response.OutputStream, ImageFormat.Jpeg);
context.Response.ContentType = "image/jpeg";
context.Response.End();
}
}
}
public bool IsReusable {
get {
return false;
}
}
}

VB


 <%@ WebHandler Language="VB" Class="Handler2" %>
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web

Public Class Handler2 : Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Using b As New Bitmap(150, 40, PixelFormat.Format32bppArgb)
Using g As Graphics = Graphics.FromImage(b)
Dim rect As New Rectangle(0, 0, 149, 39)
g.FillRectangle(Brushes.White, rect)

' Create string to draw.
Dim r As New Random()
Dim startIndex As Integer = r.[Next](1, 5)
Dim length As Integer = r.[Next](5, 10)
Dim drawString As [String] = Guid.NewGuid().ToString().Replace("-", "0").Substring(startIndex, length)

' Create font and brush.
Dim drawFont As New Font("Arial", 16, FontStyle.Italic Or FontStyle.Strikeout)
Using drawBrush As New SolidBrush(Color.Black)
' Create point for upper-left corner of drawing.
Dim drawPoint As New PointF(15, 10)

' Draw string to screen.
g.DrawRectangle(New Pen(Color.Red, 0), rect)
g.DrawString(drawString, drawFont, drawBrush, drawPoint)
End Using
b.Save(context.Response.OutputStream, ImageFormat.Jpeg)
context.Response.ContentType = "image/jpeg"
context.Response.[End]()
End Using
End Using
End Sub

Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property

End Class

Demo




How to Export Data from Gridview to Excel in Asp.net using VB.NET OR C#

How to Export Data from Gridview to Excel in Asp.net using VB.NET OR C#

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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
</asp:GridView>
</div>
<asp:Button ID="btnExport" runat="server" Text="Export to Excel" />
    </div>
    </form>
</body>
</html>

C#

using System;
using System.Data;
using System.IO;
using System.Web.UI;

public partial class demo : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridview();
        }
    }
    protected void BindGridview()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("UserId", typeof(Int32));
        dt.Columns.Add("UserName", typeof(string));
        dt.Columns.Add("Education", typeof(string));
        dt.Columns.Add("Location", typeof(string));
        dt.Rows.Add(1, "suranisizar", "B.E", "surat");
        dt.Rows.Add(2, "suranisahil", "B.E", "Bharuch");
        dt.Rows.Add(3, "suranisalim", "B.E", "Mumbai");
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void btnExport_Click(object sender, EventArgs e)
    {
        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls"));
        Response.ContentType = "application/ms-excel";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);
        gvDetails.AllowPaging = false;
        BindGridview();
        //Change the Header Row back to white color
        gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
        //Applying stlye to gridview header cells
        for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
        {
            gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
        }
        gvDetails.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
    }
}

VB

 Imports System.Data
Imports System.IO
Imports System.Web.UI

Partial Class ExportGridviewDatainVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
dt.Rows.Add(1, "suranisizar", "B.E", "surat");
dt.Rows.Add(2, "suranisahil", "B.E", "Bharuch");
dt.Rows.Add(3, "suranisalim", "B.E", "Mumbai");
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered

End Sub
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gvDetails.AllowPaging = False
BindGridview()
'Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Applying stlye to gridview header cells
For i As Integer = 0 To gvDetails.HeaderRow.Cells.Count - 1
gvDetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
Next
gvDetails.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
End Class

Demo:



Excel Demo:
 


Download Demo:

Static Constructor in C#.NET with Example

Static Constructor in C#.NET with Example 
 
using System;
namespace ConsoleApplication3
{
    class Sample
    {
        public string param1, param2;
        static Sample()
        {
            Console.WriteLine("Static Constructor");
        }
        public Sample()
        {
            param1 = "Sample";
            param2 = "Instance Constructor";
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Here Both Static and instance constructors are invoked for first instance
            Sample obj = new Sample();
            Console.WriteLine(obj.param1 + " " + obj.param2);
            // Here only instance constructor will be invoked
            Sample obj1 = new Sample();
            Console.WriteLine(obj1.param1 + " " + obj1.param2);
            Console.ReadLine();
        }
    }
}

Static Constructor
Sample Instance Constructor
Sample Instance Constructor

Private Constructor in C# with Example

Private Constructor in C# with Example

using System;
namespace ConsoleApplication3
{
    public class Sample
    {
        public string param1, param2;
        public Sample(string a, string b)
        {
            param1 = a;
            param2 = b;
        }
        private Sample()  // Private Constructor Declaration
        {
            Console.WriteLine("Private Constructor with no prameters");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            // Here we don't have chance to create instace for private constructor
            Sample obj = new Sample("Welcome", "to http://fantasyaspnet.blogspot.in/");
            Console.WriteLine(obj.param1 + " " + obj.param2);
            Console.ReadLine();
        }
    }
}

Demo:

Welcome to http://fantasyaspnet.blogspot.in/

Destructor in C# with Example

Destructor in C# with Example

Syntax:
 

class SampleA
{
    public SampleA()
    {
        // Constructor
    }
    ~SampleA()
    {
        // Destructor
    }
}


using System;
namespace ConsoleApplication3
{
    class SampleA
    {
        // Constructor
        public SampleA()
        {
            Console.WriteLine("An  Instance  Created");
        }
        // Destructor
        ~SampleA()
        {
            Console.WriteLine("An  Instance  Destroyed");
        }
    }

    class Program
    {
        public static void Test()
        {
            SampleA T = new SampleA(); // Created instance of class
        }
        static void Main(string[] args)
        {
            Test();
            GC.Collect();
            Console.ReadLine();
        }
    }
}

Output:


An instance created
An instance destroyed

Copy Constructor in C# with Example

Copy Constructor in C# with Example 


using System;
namespace ConsoleApplication3
{
    class Sample
    {
        public string param1, param2;
        public Sample(string x, string y)
        {
            param1 = x;
            param2 = y;
        }
        public Sample(Sample obj)     // Copy Constructor
        {
            param1 = obj.param1;
            param2 = obj.param2;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Sample obj = new Sample("Welcome", "http://fantasyaspnet.blogspot.in/");  // Create instance to class Sample
            Sample obj1 = new Sample(obj); // Here obj details will copied to obj1
            Console.WriteLine(obj1.param1 + " to " + obj1.param2);
            Console.ReadLine();
        }
    }
}



Welcome to http://fantasyaspnet.blogspot.in/


Friday 14 February 2014

How To Create Cascading Dropdown List in Asp.net with Example Using Jquery

How To Create Cascading Dropdown List in Asp.net with Example Using Jquery

Country Table



State Table





Region Table





.Aspx Page
 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Cascading Dropdown Example</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Country</td>
                    <td>
                        <asp:dropdownlist id="ddlcountries" runat="server"></asp:dropdownlist>
                    </td>
                </tr>
                <tr>
                    <td>State</td>
                    <td>
                        <asp:dropdownlist id="ddlstate" runat="server"></asp:dropdownlist>
                    </td>
                </tr>
                <tr>
                    <td>Region</td>
                    <td>
                        <asp:dropdownlist id="ddlcity" runat="server"></asp:dropdownlist>
                    </td>
                </tr>
            </table>
        </div>
    </form>
    <script type="text/javascript">
        $(function () {
            $('#<%=ddlstate.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
            $('#<%=ddlstate.ClientID %>').append('<option selected="selected" value="0">Select State</option>');
            $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
            $('#<%=ddlcountries.ClientID %>').change(function () {
                var country = $('#<%=ddlcountries.ClientID%>').val()
                $('#<%=ddlstate.ClientID %>').removeAttr("disabled");
                $('#<%=ddlcity.ClientID %>').empty().append('<option selected="selected" value="0">Select Region</option>');
                $('#<%=ddlcity.ClientID %>').attr('disabled', 'disabled');
                $.ajax({
                    type: "POST",
                    url: "jQueryCascadingDropdownExample.aspx/BindStates",
                    data: "{'country':'" + country + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlstate.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong')
                    }
                });
            });
            $('#<%=ddlstate.ClientID %>').change(function () {
                var stateid = $('#<%=ddlstate.ClientID%>').val()
                $('#<%=ddlcity.ClientID %>').removeAttr("disabled");
                $.ajax({
                    type: "POST",
                    url: "jQueryCascadingDropdownExample.aspx/BindRegion",
                    data: "{'state':'" + stateid + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var j = jQuery.parseJSON(msg.d);
                        var options;
                        for (var i = 0; i < j.length; i++) {
                            options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>'
                        }
                        $('#<%=ddlcity.ClientID %>').html(options)
                    },
                    error: function (data) {
                        alert('Something Went Wrong')
                    }
                });
            })
        })
    </script>
</body>
</html>



C# Code



 using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Web.Services;
using System.Web.UI.WebControls;
 public static string strcon = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true";
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindCountries();
}
}
public void BindCountries()
{
String strQuery = "select CountryID,CountryName from Country";
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Connection = con;
con.Open();
ddlcountries.DataSource = cmd.ExecuteReader();
ddlcountries.DataTextField = "CountryName";
ddlcountries.DataValueField = "CountryID";
ddlcountries.DataBind();
ddlcountries.Items.Insert(0, new ListItem("Select Country", "0"));
con.Close();
}
}
}
[WebMethod]
public static string BindStates(string country)
{
StringWriter builder = new StringWriter();
String strQuery = "select StateID,StateName from State where CountryID=@CountryID";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("@countryid", country);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select State\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["StateName"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["StateID"]+ "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select State\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}

[WebMethod]
public static string BindRegion(string state)
{
StringWriter builder = new StringWriter();
String strQuery = "select RegionID, RegionName from Region where StateID=@StateID";
DataSet ds = new DataSet();
using (SqlConnection con = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandType = CommandType.Text;
cmd.CommandText = strQuery;
cmd.Parameters.AddWithValue("@StateID", state);
cmd.Connection = con;
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Close();
}
}
DataTable dt = ds.Tables[0];
builder.WriteLine("[");
if (dt.Rows.Count > 0)
{
builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
builder.WriteLine("\"optionValue\":\"0\"},");
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
builder.WriteLine("{\"optionDisplay\":\"" + dt.Rows[i]["RegionName"] + "\",");
builder.WriteLine("\"optionValue\":\"" + dt.Rows[i]["RegionID"] + "\"},");
}
}
else
{
builder.WriteLine("{\"optionDisplay\":\"Select Region\",");
builder.WriteLine("\"optionValue\":\"0\"},");
}
string returnjson = builder.ToString().Substring(0, builder.ToString().Length - 3);
returnjson = returnjson + "]";
return returnjson.Replace("\r", "").Replace("\n", "");
}


VB Code


Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Imports System.Web.Services
Imports System.Web.UI.WebControls

Partial Class VBCode
Inherits System.Web.UI.Page
Public Shared strcon As String = "Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true"
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

If Not IsPostBack Then
BindCountries()
End If
End Sub
Public Sub BindCountries()
Dim strQuery As [String] = "select CountryID,CountryName from Country"
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
con.Open()
ddlcountries.DataSource = cmd.ExecuteReader()
ddlcountries.DataTextField = "CountryName"
ddlcountries.DataValueField = "CountryID"
ddlcountries.DataBind()
ddlcountries.Items.Insert(0, New ListItem("Select Country", "0"))
con.Close()
End Using
End Using
End Sub
<WebMethod()> _
Public Shared Function BindStates(ByVal country As String) As String
Dim builder As New StringWriter()
Dim strQuery As [String] = "select StateID,StateName from State where CountryID=@CountryID"
Dim ds As New DataSet()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Parameters.AddWithValue("@countryid", country)
cmd.Connection = con
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
End Using
End Using
Dim dt As DataTable = ds.Tables(0)
builder.WriteLine("[")
If dt.Rows.Count > 0 Then
builder.WriteLine("{""optionDisplay"":""Select State"",")
builder.WriteLine("""optionValue"":""0""},")
For i As Integer = 0 To dt.Rows.Count - 1
builder.WriteLine("{""optionDisplay"":""" & Convert.ToString(dt.Rows(i)("StateName")) & """,")
builder.WriteLine("""optionValue"":""" & Convert.ToString(dt.Rows(i)("StateID")) & """},")
Next
Else
builder.WriteLine("{""optionDisplay"":""Select State"",")
builder.WriteLine("""optionValue"":""0""},")
End If
Dim returnjson As String = builder.ToString().Substring(0, builder.ToString().Length - 3)
returnjson = returnjson & "]"
Return returnjson.Replace(vbCr, "").Replace(vbLf, "")
End Function

<WebMethod()> _
Public Shared Function BindRegion(ByVal state As String) As String
Dim builder As New StringWriter()
Dim strQuery As [String] = "select RegionID, RegionName from Region where StateID=@StateID"
Dim ds As New DataSet()
Using con As New SqlConnection(strcon)
Using cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Parameters.AddWithValue("@StateID", state)
cmd.Connection = con
con.Open()
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
con.Close()
End Using
End Using
Dim dt As DataTable = ds.Tables(0)
builder.WriteLine("[")
If dt.Rows.Count > 0 Then
builder.WriteLine("{""optionDisplay"":""Select Region"",")
builder.WriteLine("""optionValue"":""0""},")
For i As Integer = 0 To dt.Rows.Count - 1
builder.WriteLine("{""optionDisplay"":""" & Convert.ToString(dt.Rows(i)("RegionName")) & """,")
builder.WriteLine("""optionValue"":""" & Convert.ToString(dt.Rows(i)("RegionID")) & """},")
Next
Else
builder.WriteLine("{""optionDisplay"":""Select Region"",")
builder.WriteLine("""optionValue"":""0""},")
End If
Dim returnjson As String = builder.ToString().Substring(0, builder.ToString().Length - 3)
returnjson = returnjson & "]"
Return returnjson.Replace(vbCr, "").Replace(vbLf, "")
End Function
End Class


Demo: