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.