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