Pages

Showing posts with label c#. Show all posts
Showing posts with label c#. Show all posts

Friday, 12 September 2014

How to Get Data From Wikipedia Using API and jQuery in C#

How to Get Data From Wikipedia Using API and jQuery in C#
                                                                 
.Aspx File
 
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="WikirRference.aspx.vb" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="https://googledrive.com/host/0Bw4NrxH2nTVqMnliTHpSY0U4ZE0" type="text/javascript"></script>

    <script src="https://googledrive.com/host/0Bw4NrxH2nTVqYndKU2p0Z2s3M1E" type="text/javascript"></script>

    <script src="https://googledrive.com/host/0Bw4NrxH2nTVqX3VZazJtMmxSNW8" type="text/javascript"></script>
    <title></title>
    <script type="text/javascript">
        $(document).ready(function () {
        });
        function searchdata() {

            var q = $("#searchterm").val();
            $.getJSON("http://en.wikipedia.org/w/api.php?callback=?",
              {
                  srsearch: q,
                  action: "query",
                  list: "search",
                  format: "json"

              },
              function (data) {
                  $("#results").empty();
                  $("#results").append("Results for <b>" + q + "</b> </br>");
                  $("#results").append("<div>&nbsp;</div>");
                  $.each(data.query.search, function (i, item) {
                      $("#results").append("<div><a href='http://en.wikipedia.org/wiki/" + encodeURIComponent(item.title) + "'>" + item.title + "</a> : " + item.snippet + "</div>");
                  });
              });


        }

    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div style="border: 2px solid #a1a1a1; padding: 10px 40px; background: #dddddd; width: 300px; border-radius: 25px; height: 60px; text-align: left;">
            <b>Wikipedia API Search Using jQuery By http://fantasyaspnet.blogspot.in/</b><br />
            (This Wikipedia API will give the search results and references more than one.)
        </div>
        <div style="padding-left: 75px; padding-top: 15px;">
            <input id="searchterm" type="text" />
            <input id="search" type="button" value="Search" onclick="searchdata();" />
        </div>
        <div>&nbsp;</div>
        <div id="results" style="width: 300px; box-shadow: 10px 10px 5px #888888;">
        </div>
    </form>
</body>
</html>

Live Demo

Wikipedia API Search Using jQuery By http://fantasyaspnet.blogspot.in/
(This Wikipedia API will give the search results and references more than one.)
 




Thursday, 11 September 2014

How to Call C# Method/Function Using jQuery Ajax

How to Call C# Method/Function Using jQuery Ajax
                                                                 
pageUrl = '<%= ResolveUrl("~/Default.aspx/jqueryAjaxCall") %>';
Default.aspx =  Page Name and jqueryAjaxCall= c# method This is static web method.
firstName = $("#<%= txtFirstName.ClientID %>").val(); First Name parameters
lastName = $("#<%= txtLastName.ClientID %>").val();  Second Name parameters
parameter = { "firstName": firstName, "lastName": lastName }
Json format here first name and last name will we pass as the parameters to my jqueryAjaxCall method

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Call C# method/function using JQuery Ajax</title>

    <script src="Script/jquery-1.11.0.min.js" type="text/javascript"></script>

    <script type="text/javascript" language="javascript">

        function JqueryAjaxCall() {
            var pageUrl = '<%= ResolveUrl("~/Default.aspx/jqueryAjaxCall") %>';
            var firstName = $("#<%= txtFirstName.ClientID %>").val();
            var lastName = $("#<%= txtLastName.ClientID %>").val();
            var parameter = { "firstName": firstName, "lastName": lastName }

            $.ajax({
                type: 'POST',
                url: pageUrl,
                data: JSON.stringify(parameter),
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                success: function(data) {
                    onSuccess(data);
                },
                error: function(data, success, error) {
                    alert("Error : " + error);
                }
            });

            return false;
        }

        function onSuccess(data) {
            alert("welcome " + data.d + " to http://fantasyaspnet.blogspot.in/");
        }
  
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="3" cellspacing="0" style="width: 25%;">
            <tr>
                <td>
                    First Name:
                </td>
                <td>
                    <asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    Last Name:
                </td>
                <td>
                    <asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" OnClientClick="return JqueryAjaxCall();"
                        Text="Submit" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;

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

    }

    [WebMethod]
    public static string jqueryAjaxCall(string firstName, string lastName)
    {
        return firstName + " " + lastName;
    }
}

Demo:


Friday, 14 March 2014

How to Get All Files from Directory and Sub directories and Display it in Grid view C#

How to Get All Files from Directory and Sub directories and Display it in Grid view C#

C# Code:
 
 protected void BindGridview()
{
string strpath = @"C:\personal\asp.net\";
string[] folders = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories);
gvDetails.DataSource = folders;
gvDetails.DataBind();
}

VB Code:

 Protected Sub BindGridview()
Dim strpath As String = "C:\personal\asp.net\"
Dim folders As String() = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories)
gvDetails.DataSource = folders
gvDetails.DataBind()
End Sub

.Aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to Get All Files from Folder and Subfolders & Display it in Gridview in C#  asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetFiles" Text="Get Files From Folder & Sub Folders" runat="server" onclick="btnGetFiles_Click" />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>

C# Code:

using System;
using System.IO;

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

    }
    protected void btnGetFiles_Click(object sender, EventArgs e)
    {
        BindGridview();
    }
    protected void BindGridview()
    {
        string strpath = @"C:\personal\asp.net\";
        string[] folders = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories);
        gvDetails.DataSource = folders;
        gvDetails.DataBind();
    }
}

VB Code:

 Imports System.IO
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
' insert files in folder
Protected Sub btnGetFiles_Click(ByVal sender As Object, ByVal e As EventArgs)
BindGridview()
End Sub
' Bind Data to Gridview
Protected Sub BindGridview()
Dim strpath As String = "C:\personal\asp.net\"
Dim folders As String() = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories)
gvDetails.DataSource = folders
gvDetails.DataBind()
End Sub
End Class

Demo:

How to Get All Files from Folder and Subfolders & Display it in Gridview in C# asp.net

How to Get All Files from Folder and Subfolders & Display it in Gridview in C# asp.net

C# Code:
 
 protected void BindGridview()
{
string strpath = @"C:\personal\asp.net\";
string[] folders = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories);
gvDetails.DataSource = folders;
gvDetails.DataBind();
}

VB Code:

 Protected Sub BindGridview()
Dim strpath As String = "C:\personal\asp.net\"
Dim folders As String() = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories)
gvDetails.DataSource = folders
gvDetails.DataBind()
End Sub

.Aspx Code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to Get All Files from Folder and Subfolders & Display it in Gridview in C#  asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnGetFiles" Text="Get Files From Folder & Sub Folders" runat="server" onclick="btnGetFiles_Click" />
<asp:GridView ID="gvDetails" CellPadding="5" runat="server">
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
</form>
</body>
</html>

C# Code:

using System;
using System.IO;

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

    }
    protected void btnGetFiles_Click(object sender, EventArgs e)
    {
        BindGridview();
    }
    protected void BindGridview()
    {
        string strpath = @"C:\personal\asp.net\";
        string[] folders = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories);
        gvDetails.DataSource = folders;
        gvDetails.DataBind();
    }
}

VB Code:

 Imports System.IO
Partial Class VBCode
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
End Sub
' insert files in folder
Protected Sub btnGetFiles_Click(ByVal sender As Object, ByVal e As EventArgs)
BindGridview()
End Sub
' Bind Data to Gridview
Protected Sub BindGridview()
Dim strpath As String = "C:\personal\asp.net\"
Dim folders As String() = Directory.GetFiles(strpath, "*", SearchOption.AllDirectories)
gvDetails.DataSource = folders
gvDetails.DataBind()
End Sub
End Class

Demo:

How to Convert 12 Hour AM/PM Time to 24 Hours Time Format JavaScript

How to Convert 12 Hour AM/PM Time to 24 Hours Time Format JavaScript
 
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>JavaScript Convert AM/PM to 24 Hours Time</title>
<script type="text/javascript">
function Converttimeformat() {
// var time = $("#starttime").val();
var time = document.getElementById('txttime').value;
var hrs = Number(time.match(/^(\d+)/)[1]);
var mnts = Number(time.match(/:(\d+)/)[1]);
var format = time.match(/\s(.*)$/)[1];
if (format == "PM" && hrs < 12) hrs = hrs + 12;
if (format == "AM" && hrs == 12) hrs = hrs - 12;
var hours = hrs.toString();
var minutes = mnts.toString();
if (hrs < 10) hours = "0" + hours;
if (mnts < 10) minutes = "0" + minutes;
alert(hours + ":" + minutes);
}
</script>
</head>
<body>
<div>
<table>
<tr>
<td><b>Enter Time:</b></td>
<td><input type="text" id="txttime" value="10:00 PM" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnConvert" value="Convert to AM/PM" onclick="Converttimeformat()" /></td>
</tr>
</table>
</div>
</body>
</html>

Enter Time:


How to Convert AM PM Time to 24 Hour Time jQuery

How to Convert AM PM Time to 24 Hour Time jQuery
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>jQuery Convert AM / PM time to 24 hours time</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#btnConvert').click(function () {
                var time = $("#txttime").val();
                var hrs = Number(time.match(/^(\d+)/)[1]);
                var mnts = Number(time.match(/:(\d+)/)[1]);
                var format = time.match(/\s(.*)$/)[1];
                if (format == "PM" && hrs < 12) hrs = hrs + 12;
                if (format == "AM" && hrs == 12) hrs = hrs - 12;
                var hours = hrs.toString();
                var minutes = mnts.toString();
                if (hrs < 10) hours = "0" + hours;
                if (mnts < 10) minutes = "0" + minutes;
                alert(hours + ":" + minutes);
            })
        })
    </script>
</head>
<body>
    <table>
        <tr>
            <td><b>Enter Time:</b></td>
            <td>
                <input type="text" id="txttime" value="12:00 PM" /></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="button" id="btnConvert" value="Convert to AM/PM" /></td>
        </tr>
    </table>
</body>
</html>

Enter Time:


How to Check Given Date Greater than Current Date or Today Date JavaScript JQuery

How to Check Given Date Greater than Current Date or Today Date JavaScript JQuery 
 
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>How to Check Given Date Greater than Current Date or Today Date JavaScript JQuery </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        $('#btnConvert').click(function () {
            var param1 = new Date();
            var ddate = $('#txtdate').val();
            var time = $('#txttime').val();
            var hours = Number(time.match(/^(\d+)/)[1]);
            var minutes = Number(time.match(/:(\d+)/)[1]);
            var format = time.match(/\s(.*)$/)[1];
            if (format == "PM" && hours < 12) hours = hours + 12;
            if (format == "AM" && hours == 12) hours = hours - 12;
            var sHours = hours.toString();
            var sMinutes = minutes.toString();
            if (hours < 10) sHours = "0" + sHours;
            if (minutes < 10) sMinutes = "0" + sMinutes;
            ddate = ddate + " " + sHours + ":" + sMinutes + ":00";
            var date1 = new Date(ddate);
            var date2 = new Date();
            if (date1 < date2) {
                alert('Please Enter Date time Greater than Current Date time');
                $('#txtdate').focus();
                return false;
            }
        })
    })
</script>
</head>
<body>
<table>
<tr>
<td><b>Enter Date:</b></td>
<td><input type="text" id="txtdate" value="08/27/2013" /></td>
</tr>
<tr>
<td><b>Enter Time:</b></td>
<td><input type="text" id="txttime" value="10:00 PM" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="btnConvert" value="Convert to AM/PM" /></td>
</tr>
</table>
</body>
</html> <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Check Given Date Time Greater than Current Date time in JavaScript</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        $('#btnConvert').click(function () {
            var param1 = new Date();
            var ddate = $('#txtdate').val();
            var time = $('#txttime').val();
            var hours = Number(time.match(/^(\d+)/)[1]);
            var minutes = Number(time.match(/:(\d+)/)[1]);
            var format = time.match(/\s(.*)$/)[1];
            if (format == "PM" && hours < 12) hours = hours + 12;
            if (format == "AM" && hours == 12) hours = hours - 12;
            var sHours = hours.toString();
            var sMinutes = minutes.toString();
            if (hours < 10) sHours = "0" + sHours;
            if (minutes < 10) sMinutes = "0" + sMinutes;
            ddate = ddate + " " + sHours + ":" + sMinutes + ":00";
            var date1 = new Date(ddate);
            var date2 = new Date();
            if (date1 < date2) {
                alert('Please Enter Date time Greater than Current Date time');
                $('#txtdate').focus();
                return false;
            }
        })
    })
</script>
</head>
<body>
<table>
<tr>
<td><b>Enter Date:</b></td>
<td><input type="text" id="Text1" value="03/15/2013" /></td>
</tr>
<tr>
<td><b>Enter Time:</b></td>
<td><input type="text" id="Text2" value="10:00 PM" /></td>
</tr>
<tr>
<td></td>
<td><input type="button" id="Button1" value="Convert to AM/PM" /></td>
</tr>
</table>
</body>
</html

Enter Date:
Enter Time:


Saturday, 1 March 2014

How To Validate Email with Regular Expression C#

Email Validation with Regular Expression C#

Below is the Regular Expression to Validate Email Address 
 
bool isEmail = Regex.IsMatch(txtEmail.Text.Trim(), @"\A(?:[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\Z");

Sample Code:

 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Regular Expression to validate Email Address</title>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td><b>Enter Email:</b></td>
<td>
<asp:TextBox ID="txtEmail" runat="server" />
</td>
</tr>
<tr>
<td></td>
<td><asp:Button ID="btnValidate" runat="server" Text="Validate Email"
onclick="btnValidate_Click" /> </td>
</tr>
</table>
<asp:label id="lblerrormsg" runat="server" style=" font-weight:bold; " />
</form>
</body>
</html>




How To Date Greater than From Date in JavaScript C#

How To Date Greater than From Date in JavaScript C#
 
http://fantasyaspnet.blogspot.in/2013/04/jquery-datepicker-example-or-jquery.html


How To Hide DIV Elements After 5 Seconds or Some Time Delay Using jQuery in C#

How To Hide DIV Elements After 5 Seconds or Some Time Delay Using jQuery in C#
 <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>jQuery Hide DIV Elements after 10 seconds</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript">
    $(function () {
        setTimeout(function () { $("#testdiv").fadeOut(1500); }, 5000)
        $('#btnclick').click(function () {
            $('#testdiv').show();
            setTimeout(function () { $("#testdiv").fadeOut(1500); }, 5000)
        })
    })
</script>
<style type="text/css">
.content
{
border: 2px solid Red;
color: #008000;
padding: 10px;
width: 400px;
font-family:Calibri;
font-size:16pt
}
</style>
</head>
<body>
<input type="button" id="btnclick" value="Show DIV" />
<div class="content" id="testdiv" class="">
Hi, Welcome to http://fantasyaspnet.blogspot.com
It will disappear in 5 seconds!
</div>
</body>
</html>



Hi, Welcome to http://fantasyaspnet.blogspot.com It will disappear in 5 seconds!

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


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: