jQuery Tabs - UI

jquery tab
jQuery UI libaries provied good controls. jQuery UI contains tab control that is used to show tabed formatted data. We will see example how to show jquery tabs.
Before starting implementation we need to download jQuery libraries.http://jqueryui.com/download.

<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>
<script src="js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
<script src="development-bundle/ui/jquery.ui.widget.js" type="text/javascript"></script>
<script src="development-bundle/ui/jquery.ui.tabs.js" type="text/javascript"></script>

<link href="Styles/jquery-ui-1.8.18.custom.css" rel="stylesheet" type="text/css" />
<title></title>

<script type="text/javascript">
$(function () {
// Tabs
$('#tabs').tabs();
});

</script>
</head>
<body>
<form id="form1" runat="server">
<div id="tabs">

<ul>
<li><a href="#tabs-1">Tab1</a></li>
<li><a href="#tabs-2">Tab2</a></li>
<li><a href="#tabs-3">Tab3</a></li>
</ul>
<div id="tabs-1">Tab1 Contents.</div>
<div id="tabs-2">Tab2 Contents.</div>
<div id="tabs-3">Tab3 Contents.</div>

</div>
</form>
</body>
</html>

Show jQuery popup dialog

jquery dialog
In web applications we need to show popup dialog to show errors or dialog to show message or to show confirmation dailog with ok and cancel button. jQuery UI library provides easy way to show dialog as model or simple dailog. For that we need to add ui js libraries in application.

<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>
    <script src="js/jquery-ui-1.8.18.custom.min.js" type="text/javascript"></script>
    <script src="development-bundle/ui/jquery.ui.widget.js" type="text/javascript"></script>
    <script src="development-bundle/ui/jquery.ui.dialog.js" type="text/javascript"></script>
    <link href="Styles/jquery-ui-1.8.18.custom.css" rel="stylesheet" type="text/css" />
    <title>jQuery Popup</title>
    <script type="text/javascript">
        $(function () {
            // Dialog  
            $('#dialog').dialog({
                autoOpen: false,
                width: 600,
                buttons: {
                    "Ok": function () {
                        $(this).dialog("close");
                    },
                    "Cancel": function () {
                        $(this).dialog("close");
                    }
                }
            });
            // Dialog Link
            $('#btnDelete').click(function () {
                $('#dialog').dialog('open');
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="dialog" title="Dialog Title">
        <p>
            Do you want to delete record?</p>
    </div>
    <input type="button" id="btnDelete" value="Delete" />
    </form>
</body>
</html>

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++