Confirmationbox in javascript

show confirmationbox in javascript
In asp.net we need to show javascript confirmation box before doing some action.For example if we want to delete some record on the form, and we need users confirmation before deletion happens.

Sample code to show confirmation box in Javascript

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Confirmation() {
if (confirm("Do you want to delete record?") == true)
return true;
else
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Submit" onclick="return Confirmation();" />
</div>
</form>
</body>
</html>

Disable button jQuery

Disabling button after clicking on it is bit easy in jQuery.We can access button element of the page in jQuery and disable button using jquery. For that we can get button element using Id attribute selector or using class attribute selector.For example We may need to disable submit button after submitting form by clicking on it.

Sample code to disable submit button[jQuery + asp.net]

<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></title>
<script type="text/javascript">
$(document).ready(function () {
});

function Disable(btn) {
$(btn).attr("disabled", "true");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Submit" onclick="return Disable(this);" />
</div>
</form>
</body>
</html>

potentially dangerous Request error

In asp.net C# sometimes we get potentially dangerous Request error. potentially dangerous Request error comes when we try to pass special character's like <,>,:...etc. In order to solve the potentially dangerous Request error we need to set validateRequest="false" in page directive for perticular page like:

<%@ Page Language="C#" AutoEventWireup="true" <b>ValidateRequest="false"</b>%>


Or if we want to set it for whole web application page then we can set it in web.config in section like

<pages smartNavigation="false" <b>validateRequest="false"</b> enableSessionState="true"></pages>

If we are using newer version of .net framework then we need to set "requestValidationMode="2.0"" in "" in web.config like:
<httpRuntime maxRequestLength="10000" executionTimeout="3600" <b>requestValidationMode="2.0"</b>/>

Assign value using jQuery

assign values in jQuery
In asp.net applications we need to assign value in javascript or jQuery to the controls like label or hiddenfield. We will see sample code that assigns value to lable and hidden field using 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>assign value in jQuery</title>
<script type="text/javascript">
$(document).ready(function () {

});

function AssignValue() {
$("#message").html('New Value assigned');
$("#hiddenValue").val('New Value assigned');
return false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<label id="message">
Some Value</label>
<input type="submit" name="btnsubmit" id="btnsubmit" value="LogIn" onclick="return AssignValue();" />
<input type="hidden" id="hiddenValue" />
</p>
</div>
</form>
</body>
</html>

In above example if we want to assign value to hidden field and get hidden field value in code behind we need to remove "return false;" statement from jQuery code so that page will get postback.

jQuery validate form empty fields

validate empty fields using jQuery
In Web forms we need to validate fields on the form to check field should not be empty. For example for login form we need to validate textboxes for username and password to check textbox not empty.

Example to validate textbox not empty using 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>Validate empty field using jQuery</title>

<script type="text/javascript">
$(document).ready(function () {

});

function Validate() {
var username = $("#username").val();
var password = $("#pwd").val();

if (username == "" && password == "") {
alert("Enter username and password");
return false;
}

if (username == "") {
alert("Enter username");
return false;
}

if (password == "") {
alert("Enter password");
return false;
}

}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<p> 
<label for="userName">Username</label>
<input type="text" name="log" id="username" value="" size="50" tabindex="10" />
</p> 
<p> 
<label for="pwd">Password</label> 
<input type="password" name="pwd" id="pwd" value="" size="50" tabindex="20" />
</p> 
<p> 
<input type="submit"  name="btnsubmit" id="btnsubmit" value="LogIn" onclick="return Validate();"/>
</p> 
</div>
</form>
</body>
</html>

Get RadioButtonList value in jQuery

Get radiobuttonlist value using jquery
In asp.net while using radiobuttonlist we need to find selected radio buttons value in jQuery. We see example how to get value of selected radio button in jQuery.

Example 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 radiobutton value in jQuery</title>

<script type="text/javascript">
$(document).ready(function () {
$('#radiolist-container input').click(function () {
alert($(this).val());
}); 

});
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="radiolist-container">
<p><label>Get radiobutton value in jQuery</label> 
<asp:RadioButtonList ID="radioOption" runat="server"> 
<asp:ListItem Text="ASP.NET" Value="ASP.NET"></asp:ListItem> 
<asp:ListItem Text="C#" Value="C#"></asp:ListItem> 
</asp:RadioButtonList></p>
</div>
</form>
</body>
</html>

Get selected items in checkboxlist asp.net

iterate checkboxlist

When using checkbox list control in asp.net we need to find multiple selected items from Checkbox list. For example there is a Checkbox list with subject list and we need to show the items those are selected.

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<title></title> 
</head> 
<body> 
<form id="form1" runat="server"> 
<div> 
<asp:CheckBoxList ID="CheckBoxList1" runat="server"> 
<asp:ListItem Value="0">ASP.NET</asp:ListItem> 
<asp:ListItem Value="1">C#.NET</asp:ListItem> 
<asp:ListItem Value="2">VB.NET</asp:ListItem> 
<asp:ListItem Value="3">WCF</asp:ListItem> 
</asp:CheckBoxList> 
<br /> 
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Show Selected" /> 
<br /> 
<br /> 
<asp:Label ID="lblSelected" runat="server" Text=""></asp:Label> 
</div> 
</form> 
</body> 
</html> 

Code that shows selected item from checkbox list [C#]


using System.Web.UI.WebControls;

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

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            lblSelected.Text = "";

            foreach (ListItem item in CheckBoxList1.Items)
            {
                if (item.Selected == true)
                {
                    lblSelected.Text += "Selected Subject/s: " + item.Text + "
";
                }
            } 

        }
    }
}

Get checkbox control in gridview C# - findcontrol

get gridview checkbox asp.net c#
In this post we are going to see how to find checked checkboxes in gridview using c#. To find the checkboxes in gridview we have to iterate through the rows of gridview using gridviews rows collection. And then we can use findcontrol method of the row to get checkbox control. We need to pass Id of the checkbox to FindControl method.

Example to get checked checkboxes in gridview[C#]


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</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="CheckBoxSelect" 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>

</div>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</form>
</body>
</html>

In code behind on click of button we will iterate through gridviews rows and find out checked checkboxes.

using System.Data;

namespace aspnetcontrol
{
    public partial class GridviewImages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) 
        {
            if (!IsPostBack)
            {
                GridView1.DataSource = BindImageData();
                GridView1.DataBind();
            }
        }

       public DataTable BindImageData()     
        {
           
            DataTable dt = new DataTable();
           
            dt.Columns.Add(new DataColumn("ItemNo", typeof(int)));
            dt.Columns.Add(new DataColumn("ItemName", typeof(string)));
            // Create the four records
            DataRow dr = dt.NewRow();
            dr["ItemNo"] = 1;
            dr["ItemName"] = "Tea";
           
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["ItemNo"] = 2;
            dr["ItemName"] = "Coffie";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            return dt;
        }

       protected void Button1_Click(object sender, EventArgs e)
       {
           // Iterate through the Products.Rows property
           foreach (GridViewRow row in GridView1.Rows)
           {
               CheckBox cb = (CheckBox)row.FindControl("CheckBoxSelect");

               if (cb != null && cb.Checked)
               {
                   //Do some stuff
                   
               }
           }
       }
    }

asp.net add checkbox in gridview

add checkbox in gridview

In asp.net we need to add checkbox in gridview to select the row in gridview. To add checkbox in gridview we have to add ItemTemplate inside the asp:TemplateField. And inside ItemTemplate we can add checkbox control. We will how to add checkbox in gridview in asp.net using C#.

Example to add checkbox in gridview


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</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>
</div>
</form>
</body>
</html>

Below code just binds the data to gridview.

using System.Data;

namespace aspnetcontrol
{
    public partial class GridviewImages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) 
        {
            GridView1.DataSource = BindImageData();
            GridView1.DataBind();
        }

       public DataTable BindImageData()     
        {
           
            DataTable dt = new DataTable();
           
            dt.Columns.Add(new DataColumn("ItemNo", typeof(int)));
            dt.Columns.Add(new DataColumn("ItemName", typeof(string)));
            // Create the four records
            DataRow dr = dt.NewRow();
            dr["ItemNo"] = 1;
            dr["ItemName"] = "Tea";
           
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["ItemNo"] = 2;
            dr["ItemName"] = "Coffie";
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            return dt;
        }
    }
}

Images in gridview control - c# example

asp.net image in gridview
In asp.net we need to show images in gridview. To show image in gridview we have to use TemplateColumn in gridview and Image web control inside it. asp.net 2.0 have ImageField that we can use to view image in gridview.

Sample code to show image in gridview [asp.net c#]

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</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:BoundField HeaderText="Image No." DataField="ImageID">
            <ItemStyle HorizontalAlign="Center" 
              VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:ImageField DataImageUrlField="ImagePath"></asp:ImageField>
    </Columns>
   </asp:GridView>
    </div>
    </form>
</body>
</html>

Below is C# code to show image in gridview

using System;
using System.Data;

namespace aspnetcontrol
{
    public partial class GridviewImages : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e) 
        {
            GridView1.DataSource = BindImageData();
            GridView1.DataBind();
        }

       public DataTable BindImageData()     
        {
           
            DataTable dt = new DataTable();
           
            dt.Columns.Add(new DataColumn("ImageID", typeof(int)));
            dt.Columns.Add(new DataColumn("ImagePath", typeof(string)));
            // Create the four records
            DataRow dr = dt.NewRow();
            dr["ImageID"] = 1;
            dr["ImagePath"] = ResolveUrl("~/Images/image1.jpg");
           
            dt.Rows.Add(dr);
            dr = dt.NewRow();
            dr["ImageID"] = 2;
            dr["ImagePath"] = ResolveUrl("~/Images/image2.jpg");
            dt.Rows.Add(dr);
            dr = dt.NewRow();
       
            return dt;
        }
    }
}

In above code we have used TemplateCloumn of gridview and ImageField control inside it. Here we can set any datasource that contains image and bind it to gridview. Here in this example I have created sample datatable with image column and bind it to gridview to show image in gridview.

C# convert array to list

In this post we will se how to convert array to list. We need to convert array object to generic list many times in C# programming. Converting array to list can be done by various ways. We are going to see C# examples to convert array to the list.

Conversion of array to an list can be done using constructor of the generic List class. We here use constructor of List and pass array object as parameter to List constructor and then convert it to List>

c# array to list
.

Example - convert array to list [C#]:

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// String array to convert to list
 string[] strarr = new string[]
 {
  "Convert",
  "Array",
  "To",
  "list",
 };

//Now we will convert above array using new list constructor.
 List<string> arrayToList = new List<string>(strarr);
}

In above example we saw how we converted array to list using List constructor. Now we will see other way to convert Array to list. In this way we use .ToList() instance method that converts array to list. Below example shows how array get converted in to list using .ToList() parameter less instance method.

Example to convert array to list [C#]:

using System;
using System.Collections.Generic;

class Program
{    
static void Main()
{    
// String array to convert to list    
 string[] strarr = new string[]    
 {
  "Convert",
  "Array",
  "To",
  "List",
 };
//Now we will convert above array using .ToList instance method.
List<string> arrayToList = strarr.ToList();
}

Detect if JQuery dialog is open

detect if dialog is open
when using a JQuery dialog, in some cases we neeed to check if dialog is open or not. In below example we will see how do to detect if a JQuery dialog box is open or not

jQuery example that check's if dailog is open [jQuery]

<html>
<head><title></title>
<script src="jquery-1.4.1.js" ></script>
<script src="jquery-1.4.1.min.js" ></script>

<style type="text/css"> 
  .info {
   position: absolute;
   z-index: 200;
   display: none;
   text-align: center;
   background: gray;
   border: 2px solid silver;
 }
</style>
<script type="text/javascript"> 
//<![CDATA[
     $(document).ready(function () {
         initializeDialog();
         OpenDailog();
     });

     function initializeDialog() {
         $('#dialog').dialog({
             width: 650,
             modal: true,
             title: 'Dailog Title',
             buttons: { Close: function() { $(this).dialog('close'); } }
         });
     }

     function OpenDailog() {
         var $dlg = $('#dialog');
         //Here We check if dailog is open or not
         if ($dlg.dialog('isOpen') == true) {
             //Perform some operations;
         }
         $dlg.append('<p>Dailog Contents</p>');
         $dlg.dialog('open');
         $dlg.dialog('option', 'title', 'dailog Title'); 
     }
//]]>
</script>
</head>
<body>
<form action="">
<div id="dailog" class="info">
</div>
</form>
</body>
</html>


In above code if ($dlg.dialog('isOpen') == true) is imporant code that check's if jQuery dailog is open or not. You need to explicitly check == true otherwise $dlg.dialog('isOpen') will just return object only.

Click event in jQuery

jQuery mouse click event
In web application we need capture mouse click event in jQuery. To perform some clientside operations in asp.net we can easly capture mouse click event in jQuery.

jQuery mouse click event happens when we click mouse button on some spicific element on page. We can use click event to show some information box, or we can show hide div on click event of mouse...etc
Here we will look at very simple exaple of how to show hide div when we click on link

Sample code for click event in jQuery [ASP.NET]


<html>
<head><title></title>
  <script src="jquery-1.4.1.js" ></script>
  <script src="jquery-1.4.1.min.js" ></script>
    
 <style type="text/css"> 
  .info {
   position: absolute;
   z-index: 200;
   display: none;
   text-align: center;
   background: gray;
   border: 2px solid silver;
 }
</style>
 <script type="text/javascript"> 
//<![CDATA[
  $(document).ready(function(){
   $("a").click(function(){
   $(".info").show();
  });
//]]>
</script>
</head>
<body>
 <form>
 <p>
   Click on this link <a id="aspnet" href="#" >jQuery mouse clickr</a>.
 </p>
 <div class="info">
   You will see some infomation when you <b>mouse click</b> on link. 
 </div>
</form>
</body>
</html>

Mouseover event in jQuery

mouseover jquery
In web application often we need mouseover in jquery. jQuery mouseover event triggers when we take mouse over perticular DOM element on page.

We can use mouseover to show custom tooltip on link or to show mouseover context menu...etc.jQuery provides lot's of mouse event's in order to deal with clientside operation in asp.net.
Here we will look at very simple exaple of how to show hide div when we mouseover on link.

Sample to show how mouseover in jQuery works [ASP.NET]


<html>
<head><title></title>
    <script src="jquery-1.4.1.js" ></script>
    <script src="jquery-1.4.1.min.js" ></script>
    
    <style type="text/css"> 
 .info {
  position: absolute;
  z-index: 200;
  display: none;
         text-align: center;
  background: #fff;
     border: 1px solid silver;
 }
</style>
 <script type="text/javascript"> 
//<![CDATA[
        $(document).ready(function(){
            $("a").mouseover(function(){
                $(".info").show();
           });

           $("a").mouseout(function () {
               $(".info").hide();
           });
        });
//]]>
</script>
</head>
<body>
    <form>
<p>
Mouseover on this link <a id="aspnet" href="#" >jQuery mouseover</a>.
    </p>
<div class="info">
You will see some infomation when you <b>mouseover</b> on link.
And infomation will hide when you <b>mouseout</b> from link.
     </div>
</form>
</body>
</html>

String splitting C#

split string c#

C#.Net provides Split() function to split the string by the specified char and stores it in array. Split string using C# is bit easy task. In C# we can split string into substrings—such as splitting a sentence into individual words. In this case we set split char as a "," character and then it will returns an array of substrings

using System;
public class sortlist
{
  public static void Main()
  {
    string myString = "C#,VB,ASP.NET,C++";
    string[] splitedString = myString.Split(‘,’); 
    foreach(string item in splitedString)
    {
     Console.WriteLine(item);
    }
  }
}

//Output
//C#
//VB
//ASP.NET
//C++

C# sort list [Generic List<T>]

c# sort list
Generic List in C# provides easy way to sort list. In C# some times we need to add data to generic list and sort list by ascending based on our need. C# .net provides .sort method for List that can be used for sorting the contents of list. We will see example to sort list in c#.

Sample code to sort list [C#]:


using System;
using System.Collections.Generic;

public class sortlist
{
public static void Main()
{
List<string> names =  new List<string>();
names.Add("John");
names.Add("Antony");
names.Add("Mickel");
names.Add("Daniel");
names.Sort();
Console.WriteLine();
foreach(string name in names)
{
Console.WriteLine(name);
}
}
}


//Output
//Antony
//Daniel
//John
//Mickel

Get checked checkboxes in jQuery

get checked checkboxes in jquery


In this post we are going to see how to get all the checked checkboxes using jQuery. Some time in asp.net applications we need to do operations at client side on controls like checkboxes, dropdown list, buttons…etc. Here we will see how to access checkboxes at client side using jQuery and how to get checked checkboxes. To get the checked checkboxes, jQuery provides selector :checked.

Sample code to get all checked checkboxes[jQuery – ASP.Net]

<input value="1" checked type="checkbox" name="numbers" />
<input value="2" type="checkbox" name="numbers" />
<input value="3" checked type="checkbox" name="numbers" />

Now to get only the checked checkboxes we will use below line of code that will store all the checked checkboxes as an array.


$checkedCheckboxes = $("input:checkbox[name=numbers]:checked");;

We can iterate though the checked checkbox array using .each and perform some operations or can get or set values to checkboxes.


var selectedValues="";
$checkedCheckboxes.each(function () {
selectedValues +=  $(this).val() +",";
});
);

Let's put all above code togather

<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></title>
<script type="text/javascript">
$(document).ready(function () {
var selectedValues="";
$checkedCheckboxes = $("input:checkbox[name=numbers]:checked");
$checkedCheckboxes.each(function () {
selectedValues +=  $(this).val() +",";
});
alert(selectedValues);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input value="1" checked type="checkbox" name="numbers" />
<input value="2" type="checkbox" name="numbers" />
<input value="3" checked type="checkbox" name="numbers" />
</div>
</form>
</body>
</html>

//Output
//1,3

using jquery

Get IndexOf string in Javascript

string indexof in javascript
In JavaScript strings IndexOf() function is used to find position of specified character in the string. When IndexOf() method is used in javascript it returns position of first occurrence of the given character. If specified character is not found in string then it returns –1 value.

Syntax for IndexOf()


string.indexOf(searchstring, start)

Here search string is the character that is to be find and start is the position from which search to begin.

Example of IndexOf() Method [JavaScript]:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function GetStringIndex() { 
var str="Javascript IndexOf Method.";
document.write( "a is at position"+ str.indexOf("a") + "<br />");
document.write("IndexOf is at position"+ str.indexOf("IndexOf") + "<br />");
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="button" value="Submit" onclick="return GetStringIndex();" />
</div>
</form>
</body>
</html>

//Output<
//a is at position 1
//IndexOf is at position 11

Split string JavaScript

split string in javascript
In JavaScript we need to split the string to perform some operations on string. JavaScript uses Split() method to split the given string in JavaScript. Split() method basically split string into array of substrings and generates new array.

String split Syntax:


string.split(separator, limit)

Here separator is a character by which we want to separate string. and limit is to give up to how many number split the string.

Sample to split string [JavaScript]


<script type="text/javascript">
 function splitString()
 {
  var str="Split Javascript String";
  document.write(str.split(" "));
 }
</script> 


//Output
//Split, Javascript, String

In above example of string split, we give space(“ ”) character to split the string with. so it splits the string with “ “ and returns array with substrings.

Get GridView SelectedIndexChanged event asp.net

gridview selectedindexchanged event
In this post we will see how to use SelectedIndexChanged Event of GridView in ASP.Net. SelectedIndexChanged event get fired when we click select button of the gridview row. We can use this event to perform some operation on form when row is selected like call custom routines, change labels, change titles..etc.

Sample code to see how SelectedIndexChanged event in gridview works [ASP.Net, C#]:


<asp:GridView ID ="GridView1" runat="server" 
onselectedindexchanged="GridView1_SelectedIndexChanged" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" AutoGenerateSelectButton="true">

<Columns>

<asp:BoundFieldDataField="ID"HeaderText="ID"SortExpression="ID" />

<asp:BoundFieldDataField="Name"HeaderText="Name"SortExpression="Name" />

<asp:BoundFieldDataField="Address"HeaderText="Address" SortExpression="Address" />

</Columns>

</asp:GridView>

<asp:SqlDataSourceID="SqlDataSource1"runat="server" ConnectionString="<
;%$ ConnectionStrings:PersonConnectionString %>" 
SelectCommand="SELECT * FROM [PersonInfo]"></asp:SqlDataSource>
</p>

<p>
<asp:labelid="lblMessage"forecolor="Red"runat="server"/>
</p>



Code behind for selectedIndexChanged Event:






protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)

{
 
  GridViewRow row = GridView1.SelectedRow;
  
  lblMessage.Text = "Selected" + row.Cells[2].Text + ".";
}

Get Time part from datetime C#

Get time part from datetime

[C#] DateTime Format is often needed while coding in C#.net. Datetime formats are basically used for converting Date and Time into Specified String representation of DateTime.

In this post of C# Datetime Format, we will see how to get the time factor out of the DateTime. We can get Hour, Minute and Second from the DateTime. DateTime provides Properties for getting Hour, Minute and Second.

Sample code to get Hours, Minutes and Seconds from Date [C#]:

class Program  
{
 static void Main(string[] args)
  {
   DateTime date = DateTime.Now;
   Console.WriteLine("Hours= " + date.Hour);
   Console.WriteLine("Minutes= " + date.Minute);
   Console.WriteLine("Seconds= " + date.Second);
  }
}

Output of this program will show current Hours, Minutes and Seconds.

Datetime compare

compare datetime
Using C# Datetime, we can compare two dates. C# DateTime class provides Date.Compare method to compare dates. DateTime.Compare() method compares dates and returns an integer value. Using that integer value we can compare date whether date is less, or equal or greater that second date.

C# Datetime Compare Syntax:

public static int Compare(DateTime dt1,DateTime dt2)

Sample code to compare dates using DateTime.Compare() [C#]

public class StringToDateTime
    {
        public static void Main()
        {
            DateTime dt = new DateTime(2012, 1, 16);
            DateTime dt1 = new DateTime(2012, 1, 16);
            int result = DateTime.Compare(dt, dt1);

            if (result == 0)
             Console.WriteLine("Date is same as today's date");
        }
    }

//Output
//Date is same as today's date

Get DateTime Difference C#

Get DateTime difference

In [C#] DateTime Formats, C# Datetime provides verious ways to get the difference between dates. Using C# Datetime we can get difference betwwen two dates, we can get difference between days, difference between hours, difference between Minutes, difference between seconds.

DateTime class provides subtract method to get the difference between two dates.And using System.TimeSpan we can show the difference. We will see C# code that show how to use Subtract method and System.TimeSpan to calculate difference between two dates.

[C#] Example to get difference between two dates:

using System;
    namespace DateAndTimeDifferenceSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                DateTime fromdt = new DateTime(2012, 1, 16);
                DateTime todt = new DateTime(2012, 2, 17);
                TimeSpan dtDiff = todt.Subtract(fromdt);
                Console.WriteLine(dtDiff);
            }
        }
    } 

//Output wiil show difference in days like below
//32.00:00:00

Using C# Datetime we can also get the difference in Hours, Minutes, And Seconds. Let’s see the C# example that show how to calculate difference in Hr, Mins, and in Secs.

Example to get difference for Hours, Minutes, and Seconds [C#]:
class Program
    {
        static void Main(string[] args)
        {
            DateTime fromdt = new DateTime(2012, 1, 16, 22, 01, 55);
            DateTime todt = new DateTime(2012, 2, 17, 23, 15, 00);
            TimeSpan dtDiff = todt.Subtract(fromdt);
            Console.WriteLine("Hours" + dtDiff.Hours);
            Console.WriteLine("Minutes" + dtDiff.Minutes);
            Console.WriteLine("Seconds" + dtDiff.Seconds);
        }
    }

//OutPut
//Hours= 1
//Minutes= 13
//Seconds = 5

Parse date in C#

c# parse date

In this post we will look how the string with date and time to be converted to DateTime. DateTime class provides Parse() method that takes string parameter that contains date and time. We can convert below kind of string to DateTime using DateTime.Parse() method: DateTime.Parse() method converts given string representation of date and time to it’s DateTime equivalent.


Sample code to convert string to DateTime using DateTime.Parse() [C#]


using System;
 public class StringToDateTime
 {
   public static void Main()
   {
     string myDateTimeValue = "2012-01-16 15:02:26";
     DateTime myDateTime = DateTime.Parse(myDateTimeValue);
     Console.WriteLine(myDateTime);
   }
 }


//Output
//16/01/2012 15:02:26

Add Years to date

add years in date
In C# programming some times we  need to add years to the current year. This situation happens when we need to keep things in some date range. Means for example if I want to show date range from this year to next or next two years or specified years then we can use DateTime.AddYears Method.


DateTime AddYears Syntax:

public DateTime AddYears(int value);


Sample code that show how to add year in DateTime[C#] :

using System;
using System.Globalization;
public class DateTimeAddYear
{
public static void Main()
{
DateTime selectedDate = DateTime.Parse("2 Jan 2007");
selectedDate = selectedDate.AddYears(2);
Console.WriteLine(selectedDate.ToString("dd MMM yyyy"));   
}
}

//Output
//2 Jan 2009

Add days in date

add days to datetime

Some times we need to add days in the date. This is needed when we want to give some days duration to perform some actions based on date.For example if we want to publish some article for two days and then hide or delete it after two days.So to add days in given date we need to use DateTime.AddDays Method


Syntax:


public DateTime AddDays(double value)

Sample code to add days in date[C#]:


using System;
using System.Globalization;
public class DateTimeAddYear
{
public static void Main()
{
DateTime selectedDate = DateTime.Parse("12 Jan 2012");
selectedDate = selectedDate.AddDays(2);
Console.WriteLine(selectedDate.ToString("dd MMM yyyy")); 
}
}//Output
//14 Jan 2012

Get Today’s Date

Get today's date
When dealing with dates most of the time we need to get current date or today’s date in C# code to perform some operations. DateTime class provides DateTime.Today property to get today’s date. Today property returns current date only and does not include time in it so we can use Today property in code where we just need today’s date and not time. Then we can use .ToString() to format string date as per our need.


Sample code to get today’s or current date [C#]


using System;
using System.Globalization;
public class DateTimeAddYear
{
public static void Main()
{
// Get current date.
DateTime todaysDate = = DateTime.Today;
//And show today's date in needed format
Console.WriteLine(todaysDate.ToString("dd MMM yyyy"));
}
}
//Output
//12 Jan 2012

Get only date part from datetime

get date part only datetime
In some cases we need to get the date with date and time with midnight time like 00:00:00 in C# code to perform some operations. DateTime class provides DateTime.Date property to get date and time with time like 00:00:00.

Sample code to get today’s or current date [C#]


using System;
using System.Globalization;
public class DateTimeAddYear
{   
public static void Main()
{
DateTime selectedDate = DateTime.Parse("12 Jan 2012");
Console.WriteLine(selectedDate.Date);  
}
}
//Output
//2 Jan 2009

Get full name of the day C# datetime

get day name datetime c#
In most C# programs while formatting the dates we need to show complete or full name of the day. Here we are going to see how “dddd” format specifier is used to show full name of the day.

Sample code to show the full name of the day [C#]

using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateToFormat =  new DateTime(2008, 8, 29, 19, 27, 15); 
Console.WriteLine(dateToFormat.ToString("dddd"));
}
}
//Output
//Friday

Date in Month Day, Year Format (MMMM dd, yyyy)

format datetime in Month Day, Year
Some times we need to show date in Month Day, Year Format like January 12, 2012. Here we will see how to format DateTime using string formatter.

Sample code to show date time in Month Day, Year format [C#]


using System;
using System.Globalization;

public class DateTimeFomrateString
{
 public static void Main()
 {
  DateTime datetoFormat = new DateTime(2012, 1, 12);
  Console.WriteLine("Today's Date is " + datetoFormat.ToString("MMMM dd, yyyy") + ".");
 }
}
//Code will display the following output:
//Today's Date is June 10, 2011.

Here MMMM is format specifier that represents month as name like for 05 it will display May. dd is format specifier from day of the month with digits from 01 to 31 and yyyy is the format specifier with four digit number like 2012.

Date in MM-dd-yy format

get date in MM-dd-yy format
Most of the time in C# code we need to format datetime as per requirement. Here we are going to discuss how to format date in MM-dd-yy format.So when we give input date as “10-29-11” then date will get formatted like “10/29/11”.

Sample code to format date in MM-dd-yy format [C#] :


using System;
using System.Globalization;

public class DateFormatSample
{
 public static void Main()
 {
  string dateToFormat = "10-29-11";
  string strFormatPattern = "MM-dd-yy";
  DateTime formattedDate;
  DateTime.TryParseExact(dateToFormat, strFormatPattern, null, 
  DateTimeStyles.None, out formattedDate);
  Console.WriteLine("Date '{0}' Formatted to {1:d}.", dateToFormat, formattedDate);
 }
}
//    output:
//    Date '12-30-11' Formatted to 12/30/2011.

Here MM displays in format 01 to 12, dd represents Day of the month with range from 01 to 31 and yy is year from 00 to 99.

do Postback in Javascript [ASP.NET]

dopostback javascript
In this post we will see how to postback page in ASP.NET from the client side using JavaScript. In some cases we need to postback page from client side i.e. by using JavaScript.
We can use __doPostBack() to postback page from client script using JavaScript.Or we can use Page.GetPostBackEventReference() to do postback from JavaScript. When we use Page.GetPostBackEventReference() it internally get converted to __doPostBack().

Sample that shows how to do postback from JavaScript [ASP.NET, C#]:


< input type="button" id="BaseButton1" onclick="submitPage()" value="OK"/>

Now after clicking on button it will call JavaScript function that will do the postback and then in page load we will capture and perform the operation that is needed.In code behind we use Request[ "__EVENTARGUMENT"] to get the request so that we can perform some operation on that event argument.So below is JavaScript function that uses Page.GetPostBackEventReference() and do the postback from Javascript.


function submitpage() 
{ 
  // trigger postback from JavaScript
   <%= this.Page.GetPostBackEventReference(this,"Delete")%> 
} 


GetPostBackEventReference Here “this” parameter in Page.GetPostBackEventReference(this, “Delete”) is the controls id and referred to as __EVENTTARGET and accessed using Request[“__EVENTTARGET”] in code behind to determine which control caused postback from JavaScript.And “Delete” is __EVENTARGUMENT and accessed using Request[ "__EVENTARGUMENT"] in code behind.

So now in code behind we can check for Request[ "__EVENTARGUMENT"] and perform some operations based on that condition like:


protected void Page_Load(object sender, EventArgs e) 
{ 
string eventArg = Request["__EVENTARGUMENT"]; 
if (!String.IsNullOrEmpty(eventArg)) 
{ 
 if(eventArg == "Delete")
 DeleteRecords();
}
} 

private void DeleteRecords() 
{ 
 //Do something
} 

List to array c#

array to list
In this post we will se how to convert list to array.We need to convert list to array many times in C# programming. Converting list to array can be done by various ways. We are going to see C# examples to convert the list to array.

we will see the way to convert list to an array. we use .ToArray() parameter less instance method that converts list to an array. Below example shows how list get converted in to array using .ToArray() method:

Example to convert list to array [C#]

using System;
using System.Collections.Generic;

class Program
{
 static void Main()
 {
  // List to convert into Array.
  List<string> lstString = new List<string>();
  lstString.Add("Convert");
  lstString.Add("List");
  lstString.Add("TO");
  lstString.Add("Array");
  // use .ToArray() Method to convert list to array
  string[] strArray = lstString.ToArray();
 }
}

Array to List [C#]

convert array to list

Some times we need add elements of an array to list in C# programming. We can use .Add() method of List class to add array elements to the List.Using . we also can use .Add() method to while converting array to List.

We will see example that will show how used .Add method to convert array to List. Here we iterate through array elements and then one by one we add those elements to List.



using System.Collections.Generic; 

protected void Button1_Click(object sender, EventArgs e) 
{     
 string[] arrStr = { "Add", "Array", "Elements", "To", "List", "C#" };      
 List <string> strList = new List<string>();     
 foreach (string stritem in arrStr)    
 {          
  lstString.Add(stritem);    
 }      
}

Base64 to String [C#]

C# convert string to base64

In this post we will see how to convert Base64 string to string. .Net provides .FromBase64String() method in System.Convert class to convert Base64 string to string. While converting Base64 string to string it first converts base64 string to byte array and then byte array converted to string.

Sample code to convert Base64 string to string [C#]


//Convert Base64 string to string
public static string Base64ToString(string strBase64)       
{  
byte[] byteArray = Convert.FromBase64String(strBase64);            
return(System.Text.Encoding.UTF8.GetString(byteArray));        
}