Skip in Linq C#

Skip() in Linq avoids or skips the given number of elements from the sequence.

Skip() example in Linq

  protected void Page_Load(object sender, EventArgs e)
        {
            var numArr = new int[5];
            numArr[0] = 9;
            numArr[1] = 6;
            numArr[2] = 3;
            numArr[3] = 5;
            numArr[4] = 2;

            var numbers = numArr.Skip(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
// Output will be 5, 2

So in above example of skip in linq, we have numArr.Skip(3);, that will skip first three elements from array and print remaining array elements.

Take() in Linq C#

In Linq i.e. System.Linq, Take operator is used to get the first specified number of elements a sequence.

Linq Take() example

using System.Linq;
protected void Page_Load(object sender, EventArgs e)
        {
            var numArray = new int[5];
            numArray[0] = 95;
            numArray[1] = 66;
            numArray[2] = 3;
            numArray[3] = 54;
            numArray[4] = 2;


            var numbers = numArray.Take(3);
            foreach (var number in numbers)
            {
                Console.WriteLine(number);
            }
        }
//It will print 95, 66, 3.

So in above sample code of Take() we have numArray.Take(3) that means it will return us the sequence of first three elements from array.

AsEnumerable() in Linq

AsEnumerable() method in Linq is used to cast or convert given type into it's IEnumerable type. AsEnumerable() basically changes the compile time type of given type that implements IEnumerable to IEnumerable itself.

Sample code to use AsEnumerable() in Linq

 protected void Page_Load(object sender, EventArgs e)
  {
      var numArray = new int[5];
      numArray[0] = 5;
      numArray[1] = 10;
      numArray[2] = 7;
      numArray[3] = 9;
      numArray[4] = 1;

      var numbers = numArray.AsEnumerable();
      foreach (var number in numbers)
       {
          Console.WriteLine(number);
       }
  }

Convert ToList() in Linq

In C# Linq, there is .ToList() extension method that is used to convert IEnumerable to List of type. Like .ToArray(), ToList() also forces immediate query execution and stores query result in List.

Example that shows how to convert array to list

 protected void Page_Load(object sender, EventArgs e)
  {
     string[] language = { "C#", "C++", "Java", "Pascal", "Cobol" };
     List languageList = language.ToList();

     foreach (string lang in languageList)
     {
                Console.WriteLine(lang);
     }
  }

Convert ToArray in linq

In C# while using Linq, we have .ToArray() extension method that is used to convert IEnumerable to an array. .ToArray() forces immediate query execution and stores query result in an array.

Example of Linq .ToArray()

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

            var carslist =
                new List 
                        { new Cars { Company = "Maruti Suzuki", Average = 15.2 },
                          new Cars { Company = "Mercedes", Average = 18.7 },
                          new Cars { Company = "Volvo", Average = 20.0 },
                          new Cars { Company = "Hundai", Average = 12.8 } };

            var companies = carslist.Where(c => c.Average > 15)
                                         .Select(c => c.Company)
                                         .ToArray();

            foreach (var company in companies)
            {
                Console.WriteLine(company);
            }
        }

    public class Cars
    {
        public string Company { get; set; }
        public double Average { get; set; }
    }

Output:
   /*
     //Maruti Suzuki
     // Mercedes
     // Volvo
   */

In above sample code we have converted List to array using linq.

ASP.NET CompareValidator

In this post we will see how to use compare validator to compare the two input values. Using compare validator we can compare two values from two different input controls or we can compare input value with some constant or fixed value.

Example of compare validator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul style="list-style-type: none">
            <li>
                <asp:TextBox ID="txt1" runat="server" />
                =
                <asp:TextBox ID="txt2" runat="server" />
            </li>
            <li>
                <asp:Button ID="Button1" Text="Validate" runat="server" />
            </li>
        </ul>
        <br>
        <asp:CompareValidator ID="compareval" Display="dynamic" ControlToValidate="txt1"
            ControlToCompare="txt2" ForeColor="red" Type="String" EnableClientScript="false"
            Text="Values are not equal." runat="server" />
    </div>
    </form>
</body>
</html>

So in compare validator we need to set ControlToValidate and ControlToCompare in order to compare two input values.

RangeValidator to validate data in between | asp.net

From the set of validation server controlin asp.net we will see how to use RangeValidator in this post.

RangeValidator is used to check if values entered are in between specific range or not. In order to use RangeValidator, we need to add server control on web form.

RangeValidator example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Enter a number between 0 and 5:
        <br>
        <asp:TextBox ID="txtNumber" runat="server" />
        <asp:RangeValidator ID="RangeValidator1" ControlToValidate="txtNumber" MinimumValue="0"
            MaximumValue="5" Type="Integer" Text="The number should be in between 0 to 5."
            ForeColor="red" runat="server" />
        <br>
        <asp:Button ID="Button1" Text="Submit" runat="server" />
    </div>
    </form>
</body>
</html>

In order to rangevalidator to be work we need to set few properties: 1. Minimum value
2. Maximum value
3. Control to validate
4. Type of data i.e. Interger, Date...etc.
5. And the Text for error message

jQuery auto focus.

In this post we will see how to set focus automatically on input control. This is done using .focus() function in jQuery.

jQuery auto focus example

<script type="text/javascript">
   $(function () {
        $("#fName").focus();
   });
</script>

.focus()function is simple and we can call it on input control on which we need to set focus.

Below is simple full example of .focus() in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#fName").focus();
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="fName"/>
<input type="text" id="lName"/>
</div>
</form>
</body>
</html>

Using RequiredFieldValidator to validate controls | asp.net

In ASP.NET there exists a set of validation server control which are useful to validate the data on form. In this post we will see how to use RequiredFieldValidator.

RequiredFieldValidator is used to check if field on the form is not empty. In order to use RequiredFiledValidator, we need to add server control on web form. After adding control on page we need to associate the RequiredFieldValidator control to the control that we have to validate. e.g. Textbox. Also we need to set error message to show when validation fails.

RequiredFieldValidator example

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Name:<br />
        <asp:TextBox runat="server" ID="Name" />
        <asp:RequiredFieldValidator runat="server" ID="validateName" ControlToValidate="Name"
            ErrorMessage="Enter the name." ForeColor="Red" />
        <br />
        <br />
        <asp:Button runat="server" ID="btnSubmit" Text="Ok" OnClick="Post_Page" CausesValidation="" />
    </div>
    </form>
</body>
</html>

Here you will notice that the validation is happening at client side means without postback, this is because by default validator control does client side validation if browser supports DHTML. And if browser does not supports scripting then it will do server side validation, means page will postback and it will check for "Page.IsValid()" and then will return true or false.

And if we explicitly want to do the server side validation then we need to set EnableClientScript="false"

Detect IE browser | jQuery

In previous post we saw how to get IE browser in JavaScript
In this post we wiil see how to detect IE browser using jQuery. jQuery have Browser object like Navigator object in JavaScript. And using Browser object we can get Browser name, version..etc.
jQuery to get IE browser
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title></title>
</head>
<script type="text/javascript">
    function getBrowser() {
    
        if ($.browser.msie) {
            alert('Detected IE browser');
        }
    }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="getBrowser();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

Output This will show alert message Detected IE browser.

Detect IE browser | Javascript

While working with Web projects those required cross browser compatibility we often need to detect the browser type,like ie, Firefox Mozilla, or chrome...etc.

In this post we will see how to find ie browser. This is done using navigator object in JavaScript. Navigator has appName property that we can use to find ie browser.

JavaScript to detect ie

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script type="text/javascript">
    function getBrowserName()
    {
        if(navigator.appName=="Microsoft Internet Explorer") {
            alert("This is " + navigator.appName + " Browser");
        }
  }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="return getBrowserName();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

//Above code will show alert message "This is Microsoft Internet Explorer Browser"

Here we will see how to detect IE browser using jQuery

jQuery check uncheck all checkboxes in gridview

In this post we will see how to check and uncheck checkboxes in the gridview. We will check and uncheck checkboxes at client side in gridview using jquery. First we will add check boxes to gridview like:

Gridview with checkboxes

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
      CellPadding="3" BorderStyle="None" Font-Names="Arial">
      <FooterStyle></FooterStyle>
      <PagerStyle HorizontalAlign="Left"></PagerStyle>
      <HeaderStyle Font-Bold="True"></HeaderStyle>
      <Columns>
        <asp:TemplateField HeaderText="Select">
          <HeaderTemplate>
            <asp:CheckBox ID="checkAll" runat="server" Text="" onclick="javascript:CheckUnCheckAll(this);" />
          </HeaderTemplate>
          <ItemTemplate>
            <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Item No." DataField="ItemNo">
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField HeaderText="Item Name" DataField="ItemName">
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
      </Columns>
    </asp:GridView>

Here in above code we have gridview with one checkbox in header and checkboxes for all the rows. Now we have to check all the checkboxes in gridview rows when header checkbox is checked and when header checkbox is unchecked all checkbox get unchecked. Now we have to access gridview object in jquery.

$('#<%=GridView1.ClientID %>')

In order to get and perform check-uncheck operation on checkboxes we have to call Javascript function from header checkbox of the gridview and in that function we will find all row checkboxes like:

 $('#<%=GridView1.ClientID %>').find("input:checkbox")

Now by iterating through each checkbox item we can assign header checkbox's checked status to all other checkboxes.

Iterate through gridview checkboxes to check uncheck checkboxes

<script type="text/javascript">
  function CheckUnCheckAll(chk) {
     $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
          if (this != chk) {
              this.checked = chk.checked;
            }
           });
      }
 </script>

Example to check-uncheck all checkboxes in gridview

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      <title>Check all checkboxes in gridview using jQuery</title>
    <script type="text/javascript">
        function CheckUnCheckAll(chk) {
            $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
                if (this != chk) {
                    this.checked = chk.checked;
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
            CellPadding="3" BorderStyle="None" Font-Names="Arial">
            <FooterStyle></FooterStyle>
            <PagerStyle HorizontalAlign="Left"></PagerStyle>
            <HeaderStyle Font-Bold="True"></HeaderStyle>
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <HeaderTemplate>
                        <asp:CheckBox ID="checkAll" runat="server" Text="" onclick="javascript:CheckUnCheckAll(this);" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Item No." DataField="ItemNo">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField HeaderText="Item Name" DataField="ItemName">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
            </Columns>
        </asp:GridView>
        <input type="button" id="submit" value="Submit" />
    </div>
    </form>
</body>
</html>

jQuery call page codebehind method

In asp.net application sometimes we need to call codebehind method from client script. In this post we will see how to call codebehind page method using jquery ajax.

To call codebehind page method from jquery we need to make method static. Also we need to add [WebMethod] attribute for method. So the code behind method will look like:

 [WebMethod]
  public static string GetMessage()
  {
   return "Codebehind method call...";
  }

We also need to add namespace using System.Web.Services; to add [WebMethod] attribute to code behind method.
Now we can call this codebehind method using jquery ajax like

var loc = window.location.href;
$.ajax({
         type: 'POST',
          url: loc + "/GetMessage",
          data: "{}",
          contentType: "application/json; charset=utf-8"
        
        })
        .success(function (response) {
          alert(response.d);

        })
        .error(function (response) {
          alert(response.d);
        });

Here using window.location.href we are getting url of aspx page and by appending method name to it we can call code behind method.

Below code demonstrats how to call codebehind method using jquery ajax and json

jQuery ajax call codebehind page method

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
var loc = window.location.href;
$("#btnClick").click(function (event) {
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

Below is the code behind method that will get called by jquery ajax call:

using System;
using System.Web.Services;

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

    }

    [WebMethod]
    public static string GetMessage()
    {
      return "Codebehind method call...";
    }
  }
}

Remove Hide blogger|blogspot header navbar

Blogger or Blogspot is the easy way to write blogs. In blogger by default it shows header navbar on top. To hide blogspot|blogger navbar from header follow the below steps:
1. Login to blogger account.
2. Go to Template in new blogger view
3. Then click on Edit Html.

hide remove blogspot header navbar using css

4. Search for <b:skin>
5. Below that add css:
#navbar-iframe
{
height:0px;
visibility:hidden;
display:none;
}
This will hide or disable the blogger default header navbar.

jQuery ajax handle exception thrown by wcf

When we work with jQuery Ajax call to WCF, it may possible that WCF service will thow an exception. And we need to catch that exception in jquery ajax error routine. In order to show or get exception thrown by service we need to configure includeExceptionDetailInFaults="True" for in behavior like:

<serviceBehaviors>
  <behavior name="">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="true" />
  </behavior>
</serviceBehaviors>

Now when jquery ajax call revices error then exception comes in resposeText as Message.But we need extract Message from responseText as responseText comes as cominations of error details. This can be done using jQuery.parseJSON like:



 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
        });

Now to get Message part we can use r.Message. This will give you the message that is sent by exception in wcf service.


 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
        });

Code for jQuery ajax handle exception thrown by wcf

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
          alert("StackTrace: " + r.StackTrace);
          alert("ExceptionType: " + r.ExceptionType);
          alert("ERROR" + response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

Note: To test example of catch exception in jquery ajax thrown by wcf service, just throw an application exception or Exception with some message like:

    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      //return "WCF" + message;
      throw  new  ApplicationException("This is exception");
    }

Configure wcf service to call in jquery ajax json

In previous post we saw how to create wcf service to be get called by jquery ajax and json. After creating wcf service we need to configure wcf service in web.config in order to make it accessible.

wcf service configuration for jquery ajax call

Configure wcf service

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="GetJson">
          <enableWebScript />
        </behavior>
        <behavior name="PostJson">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="aspnetcontrol.Service1">
        <endpoint address="get-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="GetJson"
                  contract="aspnetcontrol.Service1" />
    
        <endpoint address="post-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="PostJson"
                  contract="aspnetcontrol.Service1" />
      </service>
    </services>
  </system.serviceModel>

Create wcf service to call by jquery ajax json

In this post we will see how to create wcf service in C# that we can call through jquery ajax and json. The namespaces we need in wcf service are System.ServiceModel, System.ServiceModel.Web and System.ServiceModel.Activation.

create wcf service to be called by jquery ajax json

Example- WCF service to call by jquery ajax json

using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Web;

namespace aspnetcontrol
{
  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class Service1 
  {
    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      return "WCF" + message;
    }
  }
}

Note: In above code important attributes are [ServiceContract(Namespace = "")], [OperationContract] and [WebGet()]. ServiceContract specifies that class defines service contract in application.
OperationContract specifies that a method defines and operation that is part of web service contract.
WebGet indicates service operation is logically a retrieval operation. In this way we can create wcf service to be called using jquery ajax json. In order to make service accessible we need to configure wcf service in web.config.

jQuery Ajax call to WCF service

In jQuery we can perform an asynchronous HTTP (Ajax) request. In this post we will see simple example of how jquery Ajax call to WCF service works. We can call wcf service using jquery ajax and json.

use jquery ajax to call wcf service
We can use $.ajax to call the wcf service like:
 var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });


Here in above code snippet we have set various parameters for jquery ajax call like: type: 'GET' - means request is of type GET and not POST
url: '', here we have mentioned the url of wcf service, where Service1.svc is wcf service name, get-json is address set in the web.config wcf service and GetMessage is actual method in wcf service.
data: dto is the parameter data that we need to pass to wcf service method.

Example jquery ajax call to wcf service

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
   $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

In above example we can type some message in textbox and pass message to wcf service using jquery ajax call and get it in respose back.

Note: To run above example we need to create wcf service and configure wcf service endpoint in web.config file properly

jquery set dropdownlist exact text

We have seen how to set selected option in dropdown list by text here set dropdownlist selected option by text. In that example we used :contains selector that will look for the text and the set text in dropdownlist as selected.

dropdownlist set exact selected text
But if dropdownlist have items with same texts instance then :contains selector will get all the items with matched text. This might show last matched item selected in dropdownlist. In this case we need to use alternate way to get exact text in dropdownlist and then set it selected.

Example to set selected option in dropdown by exact text [jquery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>set dropdown value</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#go").click(function () {
        var inputText = $("#inputText").val();
        $("#numbers").each(function () {
          $('option', this).each(function () {
            if ($.trim($(this).text().toLowerCase()) == $.trim(inputText.toLowerCase())) {
              $(this).attr('selected', 'selected');
            };
          });
         });
       });
    });
 </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <label>Enter value from dropdown</label>
    <input type="text" id="inputText" />
    <asp:DropDownList ID="numbers" runat="server">
      <asp:ListItem Text="This is one" Value="1"></asp:ListItem>
      <asp:ListItem Text="This is one?" Value="2"></asp:ListItem>
      <asp:ListItem Text="This is three" Value="3"></asp:ListItem>
    </asp:DropDownList>
  </div>
  <input type="button" id="go" value="Go" />
  </form>
</body>
</html>

Summary: So by using :contains it might not work for multiple items with istance of same text. But we can iterate through dropdown items and then by matching exact text we can set dropdown list text selected.

Dropdownlist set selected value

In this post we will see in jquery how toset dropdown list value or selected option by it's value. For that we simply need to get object of dropdown list in jquery and then we can set selected option by using val(). of dropdownlist.

jquery dropdownlist set selected value

Example: set dropdown list selected option by value [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>jQuery set dropdown list selected option by value</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#go").click(function () {
          var inputText = $("#inputText").val();
          $("#numbers").val(inputText);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Enter value between 1-3</label>
      <input type="text" id="inputText"/>
    <asp:DropDownList ID="numbers" runat="server">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <input type="button" id="go" value="Go" />
    </form>
</body>
</html>

Summary: So in short we can use jquery to set dropdownlist item value like $("#numbers").val(inputText);. we can also set dropdown list selected option by using text like Set selected value by text.

Assign value to span - jquery

In this post we will see set a value to span tag using JQuer. To change value of span we can access span tag directly like $('span') and then using its .html() method we can assign some text to it.

assign value to span jquery

Example to assign text to span [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Assign value to span in jQuery</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#submitbtn").click(function () {
          var inputValue = $("#inputText").val();
          $('span').html(inputValue);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
       <label>Type some text here to assign to span</label>
        <input type="text" id="inputText"/>
        <input type="button" id="submitbtn" value="Submit" /><br/>
        <span style="width:500px;height:120px; background-color:thistle">&nbsp;</span>
    </div>
    </form>
</body>
</html>

Summary:So to replace span tag text we get the object of span tag like $('span') and using .html() we can change value of span.

Set selected option by text of dropdownlist


In this post we will see how to set selected option by text to dropdownlist. In web application we need to set dropdownlist value at client side. By using option property of dropdown list we will check if dropdown contains text that we want to set And after that using selected attribute we will set it true so that it will show the option selected that we have set using text.
set selected option in dropdownlist using jquery

Sample to set selected option by text to dropdownlist[jQuery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Set dropdownlist selected option by text</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#go").click(function () {
         var inputText = $("#inputText").val();
          $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); 
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Enter value between 1-3</label>
      <input type="text" id="inputText"/>
    <asp:DropDownList ID="numbers" runat="server">
    <asp:ListItem Text="1" Value="1"></asp:ListItem>
    <asp:ListItem Text="2" Value="2"></asp:ListItem>
    <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
    </div>
    <input type="button" id="go" value="Go" />
    </form>
</body>
</html>


Summary:By using $("#numbers option:contains(" + inputText + ")").attr('selected', 'selected'); we have dynamically set the selected option of a drop-down list using JQuery.We can set selected option of dropdown list by it's value likeset selected option of dropdown box by value

Set value to textarea - jQuery

In this post we will see how to set value to textarea in jQuery. To assign value to textarea in jquery we can use .val() method of textarea. In example we will take value from input testbox and assign it to textarea.

set value to textarea in jquery

Example to set value to textarea [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/i18n/jquery-ui-i18n.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/ui-lightness/jquery-ui.css" type="text/css" media="all" />
    <title>Set textarea value in jQuery</title>
    <script type="text/javascript">
      $(document).ready(function () {
        $("#submitbtn").click(function () {
          var inputVal = $("#inputText").val();
          $("#txtMessage").val(inputVal);
        });
      });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <label>Type Text here</label>
        <input type="text" id="inputText" /><br/>
        <textarea cols="50" rows="5" id="txtMessage"></textarea><br/>
        <input type="button" id="submitbtn" value="Submit" />
    </div>
    </form>
</body>
</html>

Regex for email validation JavaScript

In this post we will see how to validate email format in Javascript using regular expression. We can use regular expression (/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i) to validate the email address in javascript.

Regular expression to validate email format in JavaScript

Example of email validation using regex in javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Regex to validate email format in JavaScript</title>
  <script language="javascript" type="text/javascript">
    function Validate() {
      var emailRegex = new RegExp(/^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$/i);
      var emailAddress = document.getElementById("<%= txtemail.ClientID %>").value;
      var valid = emailRegex.test(emailAddress);
      if (!valid) {
        alert("Invalid e-mail address");
        return false;
      } else
        return true;
    }
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox runat="server" ID="txtemail"></asp:TextBox>
    <asp:Button runat="server" ID="Send" OnClientClick="return Validate();" Text="Send" />
  </div>
  </form>
</body>
</html>

Validate email format - RegularExpressionValidator

In asp.net in order to validate email address format we can use RegularExpressionValidator. We will see how to use RegularExpressionValidator to validate the email address format.For that we need to specify the Regular expression or regex in ValidationExpression property of the RegularExpressionValidator. Also we need to specify few other properties like ErrorMessage to display error message when email address is invalid. also we need to specify ControlToValidate property where we have to give textbox controls name in which user enters email address.

Validate email address using regular expression validator

Example to validate email address using RegularExpressionValidator

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>Validate email format </title>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:TextBox ID="txtEmail" runat="server" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
    <asp:RegularExpressionValidator ID="validateEmail" runat="server" ErrorMessage="Invalid email."
      ControlToValidate="txtEmail" ValidationExpression="^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$" />
  </div>
  </form>
</body>


Also we need to check !Page.IsValid in event hadler of control like button or link...etc like
  protected void btnSubmit_Click(object sender, EventArgs e)
    {
      if (!Page.IsValid)
        return;
    }

Remove special characters - jQuery

In this post we will see how to remove special characters like !,@,$,*,^ ...etc. from the string. For that we need to specify the special characters in regular expressions. Then by passing specified regular expression to .replace method in jquery and replace it with '' blank.

remove special characters from string in jquery

Example to remove special characters from string - jquery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Remove special character fromstring</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#Send").click(function () {
                var originalstring = $("#txtinput").val();
                var filteredString = originalstring.toLowerCase().replace( /[\*\^\'\!\@\$]/g , '');
                alert(filteredString);
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:TextBox runat="server" ID="txtinput"></asp:TextBox>
    <asp:Button runat="server" ID="Send" Text="Send" />
    </div>
    </form>
</body>
</html>


We can use regular expressions to define the special character set that we need to remove from string. so if you want to remove * from the string the regular expression will be /[\*]/g. Now if you want to remove ! also the add ! to regular expression like /[\*\!]/g and so on.

c# regex for email address

In c# while dealing with email we need to validate email address. In order to validate email address we just check whether the email address format is correct or not. In C# we can use System.Text.RegularExpressions namesapce to match the email address for validation. In Regular Expressions namespace we have Regex class and from which .Match() method can be used to match the email address with the regular express defined using Regex class.

c# regex for email address

C# code to validate email format.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>C# validate email format regex</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox runat="server" ID="txtemail"></asp:TextBox>
        <asp:Button runat="server" ID="Send" OnClick="Send_Click" Text="Send" />
    </div>
    </form>
</body>
</html>

using System;
using System.Text.RegularExpressions;
public partial class Csharpregularexpressionemail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        protected void Send_Click(object sender, EventArgs e)
        {
            ValidateEmail();
        }
        private void ValidateEmail()
        {
            string email = txtemail.Text;
            Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
            Match match = regex.Match(email);
            if (match.Success)
                Response.Write(email + " is corrct");
            else
                Response.Write(email + " is incorrct");
        }
    }


In above example we have specified format for email regex using constructure call of Regex class. Then we have used .Match method to match the regular express pattern for email to match. And after that we have checked if match is successfull or not.

.parent() - Get the parent of element jQuery

Get the parent of element
In web applications while working with clientside we may need to get parent element of elected element. jQuery provides function .parent() that we can use to easily get parent of the element.

Here we will see example where we have link inside div and on clicking on link we will get it's parent div.

Code to get parent of element [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Get parent of element</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#submitbtn").click(function () {
                var parent = $(this).parent();
                alert(parent.text());
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div style="border:1px blue solid; background-color:seashell; width:200px; height:100px;">
       This is parent
       <br/>
       <input type="button" id="submitbtn" value="Click Me"/>
    </div>
    </form>
</body>
</html>

Remove css style dynamically in jquery

remove css style dynamically in jquery
Here we will see how to remove css style of the element in jquery. In web applications we need to remove css style dynamically to give user friendly ui effects and for that we can use .removeClass() function in jquery. Here we will see example of div in which when user clicks on link it will change color of div by applying css style dynamically.

Example to remove css style dynamically

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Remove css style dynamically</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#clickme").click(function () {
                $("#dynamic-style").removeClass("myStyle");
            });
        });
    </script>
    <style type="text/css">
        .myStyle
        {
            width: 500px;
            height: 300px;
            background-color: wheat;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <a href="#" id="clickme">Change</a>
    <div id="dynamic-style" class="myStyle">
        Click change to change color.
    </div>
    </form>
</body>
</html>

Add css style dynamically in jquery

add css style dynamically injquery

In this post we will see how to add css style to element in jquery. In web applications we need to add css style dynamically to give user friendly ui effects and for that we can use .addClass() function in jquery. Here we will see example of div in which when user clicks on link it will change color of div by applying css style dynamically.

Example to add css style dynamically

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title>Add css style dynamically</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#clickme").click(function () {
                $("#dynamic-style").addClass("newStyle");
            });
        });
    </script>
    <style type="text/css">
        .newStyle
        {
            width: 500px;
            height: 300px;
            background-color: wheat;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <a href="#" id="clickme">Change</a>
    <div id="dynamic-style">
        Click change to change color.
    </div>
    </form>
</body>
</html>

Get html control value in code behind without runat = server

access html control value in codebehind without runat server
In asp.net application we need to access value of html control in code behind without runat="server". For that purpose we can use name property of control. And Request.Form we can get value to code behind.So if we have html text input and you want to pass value of html input to code behind set it name property like <input name="username" />  and access it using Rquest.Form["usename"] you will get value to code behind of control without runat="server".

Code to get html control value to code behind without runat server

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
  <script type="text/javascript">
      function SubmitForm() {
         var theform;
          if (window.navigator.appName.toUpperCase().indexOf("NETSCAPE") > -1) {
              theform = document.forms["form1"];
          }
          else {
              theform = document.forms.form1;
          }
          theform.__EVENTTARGET = "btn";   
          theform.__EVENTARGUMENT = "";
          theform.submit();
      }    
</script>  
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="text" id="username" name="username" />
        <input type="button" id="btn" onclick="SubmitForm()"  value="GO"/>
    </div>
    </form>
</body>
</html>


Code behind to access html control value


using System;

namespace aspnetcontrol
{
    public partial class Getvaluewithoutrunatservercontrol : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string value = Request.Form["username"];
            Response.Write(value);
        }
    }
}

Get gridview checkbox value jQuery

get gridview selected checkboxes in jquery
In asp.net gridview we show checkboxes to select rows. Some times we need to get checked checkboxes in jQuery to perform some client side operations. in jQuery we need to first get object of gridview and then need to find checked checkboxes inside gridview.

Example to get gridview checked checkboxes in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/i18n/jquery-ui-i18n.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/ui-lightness/jquery-ui.css" type="text/css"/>
    <title>Get checkboxes in gridview using jQuery</title>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#submit").click(function () {
               var $checkedCheckBoxes = $('#<%=GridView1.ClientID %>').find("input:checkbox:checked");
            });
        });
      
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
            CellPadding="3" BorderStyle="None" Font-Names="Arial">
            <FooterStyle></FooterStyle>
            <PagerStyle HorizontalAlign="Left"></PagerStyle>
            <HeaderStyle Font-Bold="True"></HeaderStyle>
            <Columns>
                <asp:TemplateField HeaderText="Select">
                   <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Item No." DataField="ItemNo">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField HeaderText="Item Name" DataField="ItemName">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
            </Columns>
        </asp:GridView>
        <input type="button" id="submit" value="Submit"/>
    </div>
    </form>
</body>
</html>

Jquery- Get hiddenfield value in user control

get value of dynamic hiddenfield
In this post we will see how to get value of dynamically loaded hiddenfield value in jQuery. This happens when we use user control in page. In such cases id of hiddenfield get changed and so hiddenfield is not accessible from javascript or jQuery. We can't access hiddenfield using class selector also because hidden field don't have class property. In this case we can use "ClientIDMode" property and set it to ClientIDMode="Static". When we set ClientIDMode="Static" it will not set dynamic id to hidden field. And now we can access it in regular way.

Code to get hiddenfield value in user control [jQuery]

You can set ClientIDMode property of hidden field in user control like:

<asp:HiddenField runat="server" ID="hiddenValue" ClientIDMode="Static" value="Some Value" />

And in jQuery you can access it as like:
   <script type="text/javascript">
        $(document).ready(function () {
            $("#submitbtn").click(function () {
                var hiddenValue = $("#hiddenValue").val();
                alert(hiddenValue);
            });
        });
    </script>

Summary: After setting ClientIDMode="Static" it will not assing dynamic id to hiddenfield and we can access hiddenfield as usual.

Get textarea value in jQuery

textarea value using jQuery

In web applications while using textarea control, we need to get the value of textarea at client side. In this post we will see example of how to get value of textarea in jQuery.

Example to get textarea value in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="development-bundle/jquery-1.7.1.js" type="text/javascript"></script>
<script src="js/jquery-1.7.1.min.js" type="text/javascript"></script>
<title>Get textarea value in jQuery</title>
<script type="text/javascript">
$(document).ready(function () {
$("#submitbtn").click(function () {
var textAreaValue = $("#txtMessage").text();
alert(textAreaValue);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<textarea cols="50" rows="5" id="txtMessage"></textarea>
<input type="button" id="submitbtn" value="Submit" />
</div>
</form>
</body>
</html>

Assign dropdown value to other dropdown in jquery

set dropdown value to other dropdown in jquery
While woking with clientside stuff in asp.net we need to assign value of one dropdown to other dropdown. In this post we will see how to assign dropdown value to other dropdown.

Example to assign value from dropdown to other dropdown.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title>Get dropdown value</title>
<script type="text/javascript">
$(document).ready(function () {
$("#topics").change(function () {
var text = $("#topics option:selected").text();
var value = $("#topics option:selected").val();
$("#topics1").val(value);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="topics" runat="server">
<asp:ListItem Text="C#" Value="1"></asp:ListItem>
<asp:ListItem Text="jQuery" Value="2"></asp:ListItem>
<asp:ListItem Text="ASP.NET" Value="3"></asp:ListItem>
</asp:DropDownList>

<br/><br/>
<asp:DropDownList ID="topics1" runat="server">
<asp:ListItem Text="C#" Value="1"></asp:ListItem>
<asp:ListItem Text="jQuery" Value="2"></asp:ListItem>
<asp:ListItem Text="ASP.NET" Value="3"></asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
Output

Image click event in jquery

Image click event in jQuery

In this post we are going to see how to get click event of image. This can be done by using either id jquery selector or css selector. We will see both the examples to get image click in jquery.

Image click event using id selector [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title>Get Image click event</title>
<script type="text/javascript">
$(document).ready(function () {
$("#tulips").click(function () {
alert("Image click in jquery");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="Image/Tulips.jpg"  runat="server" id="tulips" alt="image click in jquery"/>
</div>
</form>
</body>
</html>

Image click event using css selector [jQuery]

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title>Get Image click event</title>
<script type="text/javascript">
$(document).ready(function () {
$(".imagecss").click(function () {
alert("Image click in jquery");
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<img src="Image/Tulips.jpg"  runat="server" id="tulips" alt="image click in jquery" class="imagecss"/>
</div>
</form>
</body>
</html>

Convert Date to culture specific format

datetime culture
In C# we need to show date format as per culture.To convert datetime in culture specific format we need to use CultureInfo class in .ToString constructor with culture code like for US culture pass "en-US". We will see here few examples to format date as per culture.

Code to format date in US culture [C#]

using System;
 public class StringToDateTime
 {
   public static void Main()
   {
     var myDateTimeValue = "2012-01-16 15:02:26";
     DateTime myDateTime = DateTime.Parse(myDateTimeValue);
     var dateingddmmyy = myDateTime.ToString(new CultureInfo("en-US"));
     Console.Write(dateingddmmyy);
   }
 }

Code to convert date in sanskrit Indian culture [C#]

using System;
 public class StringToDateTime
 {
   public static void Main()
   {
     var myDateTimeValue = "2012-01-16 15:02:26";
     DateTime myDateTime = DateTime.Parse(myDateTimeValue);
     var dateingddmmyy = myDateTime.ToString(new CultureInfo("sa-IN"));
     Console.Write(dateingddmmyy);
   }
 }


Code to convert date in Swedish culture [C#]

using System;
 public class StringToDateTime
 {
   public static void Main()
   {
     var myDateTimeValue = "2012-01-16 15:02:26";
     DateTime myDateTime = DateTime.Parse(myDateTimeValue);
     var dateingddmmyy = myDateTime.ToString(new CultureInfo("sv-SE"));
     Console.Write(dateingddmmyy);
   }
 }

Convert date to ""dd/mm/yyyy" format C#

format datetime in dd/mm/yyyy

In c# we need to convert datetime in different formats.In this post we will see how to get datetime in "dd/mm/yyyy" format.To parse datetime in "dd/mm/yyyy" format we need to use string formatter "dd/mm/yyyy" in .ToString() constructor.

Code to get datetime in dd/mm/yyyy format [C#]

using System;
 public class StringToDateTime
 {
   public static void Main()
   {
     var myDateTimeValue = "2012-01-16 15:02:26";
     DateTime myDateTime = DateTime.Parse(myDateTimeValue);
     var dateingddmmyy = myDateTime.ToString("dd/mm/yyyy");
     Console.Write(dateingddmmyy);
   }
 }
 

Get dropdown selected item onchange in jQuery

get dropdown list selected item onchange in jquery
When using dropdown list in asp.net application, we need to get value of selected item on onchange event of dropdown. In this post we will see example of how to get value of selected item using onchange event of dropdown.

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title>Get dropdown value</title>
<script type="text/javascript">
$(document).ready(function () {
$("#topics").change (function () {
var text = $("#topics option:selected").text();
var value = $("#topics option:selected").val();
alert("Selected text=" + text + " Selected value= " + value);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="topics" runat="server">
<asp:ListItem Text="C#" Value="1"></asp:ListItem>
<asp:ListItem Text="jQuery" Value="2"></asp:ListItem>
<asp:ListItem Text="ASP.NET" Value="3"></asp:ListItem>
</asp:DropDownList>
</div>
</form>
</body>
</html>
Output

Get dropdownlist selected value in jQuery

get dropdownlist selected value in jquery
In web application we need to get dropdown value at client side. We will see the example of how to get dropdown value in jQuery.

Code to get dropdown value in jQuery


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"> type="text/javascript"> </script>
  <title>Get dropdown value</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#go").click(function () {
        var text = $("#numbers option:selected").text();
        var value = $("#numbers option:selected").val();
        alert("Selected text=" + text + " Selected value= " + value);
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <asp:DropDownList ID="numbers" runat="server">
      <asp:ListItem Text="1" Value="1"></asp:ListItem>
      <asp:ListItem Text="2" Value="2"></asp:ListItem>
      <asp:ListItem Text="3" Value="3"></asp:ListItem>
    </asp:DropDownList>
  </div>
  <input type="button" id="go" value="Go" />
  </form>
</body>
</html>

Get radio button value in jQuery

Get radio button value in jquery
When using radio buttons in web application we need to get value of radio buttons at clientside. We can use jQuery to get radio button value in jQuery.

Code that shows how to get radio button value in jQuery

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<title>Get radio button value</title>
<script type="text/javascript">
$(document).ready(function () {
$("#submit").click(function () {
var number = $("input[@name=numbers]:checked").val();
alert(number);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="radio" name="numbers" value="0" checked="checked" style="display:none" /> 
<input type="radio" name="numbers" value="1" /> 
<input type="radio" name="numbers" value="2" /> 
<input type="radio" name="numbers" value="3" /> 
<input id="submit" type="button" value="Submit"/>
</div>
</form>
</body>
</html>
Output