Archive

Archive for September, 2011

Get Value of checked item in CheckListBox

September 28, 2011 Leave a comment

Hi all,

try this example to Get Value of checked item in CheckListBox using Javascript

1) Add this Javascript code :-

<script language="javascript" type="text/javascript">
        function CheckItem() {
            var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>').childNodes[0];
            alert(tbl.childNodes[i].childNodes.length);
            for (var i = 0; i < tbl.childNodes.length; i++) {
                for (var k = 0; k < tbl.childNodes[i].childNodes.length; k++) {
                    if (tbl.childNodes[i].childNodes[k].nodeName == "TD") {
                        var currentTD = tbl.childNodes[i].childNodes[k];
                        for (var j = 0; j < currentTD.childNodes.length; j++) {
                            if (currentTD.childNodes[j].nodeName == "SPAN") {
                                var currentSpan = currentTD.childNodes[j];
                                for (var l = 0; l < currentSpan.childNodes.length; l++) {
                                    if (currentSpan.childNodes[l].nodeName == "INPUT" && currentSpan.childNodes[l].type == "checkbox") {
                                        var currentChkBox = currentSpan.childNodes[l];
                                       
                                        if (currentChkBox.checked) {
                                            alert(currentSpan.alt);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
</script>

and HTML Code will be :-

<asp:CheckBoxList ID="CheckBoxList1" runat="server"OnDataBound="CheckBoxList1_DataBound" AppendDataBoundItems="true" >
    </asp:CheckBoxList>
     <input id="Button1" type="button" value="button" onclick="javascript:CheckItem();" />

and in code behind :-

</pre>
&nbsp;

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            CheckBoxList1.DataSource = BindUsers();
            CheckBoxList1.DataTextField = "User_Name";
            CheckBoxList1.DataValueField = "User_ID";
            CheckBoxList1.DataBind();
        }

    }
    protected void CheckBoxList1_DataBound(object sender, EventArgs e)
    {
        CheckBoxList chkList = (CheckBoxList)(sender);
        foreach (ListItem item in chkList.Items)
        {
            item.Attributes.Add("alt", item.Value);
        }
    }
 

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, Javascript

Call Page Method Using Javascript

September 24, 2011 Leave a comment

Hi all,

Try this example to Call Page Method Using Client Side -Javascript in ASP.Net

ASP.Net AJAX ScriptManager allows you to call Server Side ASP.net methods from client side without any PostBack using PageMethods. Actually it is an AJAX call to the server but it allows us to call the method or function defined server side.

Enabling PageMethods
The first thing you need to do is add a ASP.Net AJAX ScriptManager to the page and set itsEnablePageMethods property to true as shown below

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

HTML Markup :-

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<div>
Your Name :
<asp:TextBox ID="txtUserName" runat="server" ></asp:TextBox>
<input id="btnGetTime" type="button" value="Show Current Time" onclick="ShowCurrentTime()"/>
</div>
</form>

Client Side Method :-

<script type="text/javascript">
function ShowCurrentTime() {
PageMethods.GetCurrentTime(document.getElementById("<%=txtUserName.ClientID%>").value, OnSuccess);
}
function OnSuccess(response, userContext, methodName) {
alert(response);
}
</script>

Server Side Methods :-

[System.Web.Services.WebMethod]
publicstaticstring GetCurrentTime(string name)
{
return"Hello " + name + Environment.NewLine + "The Current Time is: "
        + DateTime.Now.ToString();
}

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

JQuery to Validate File Upload Extension

September 19, 2011 Leave a comment

Hi all,

try this example to use JQuery to Validate file Upload Extension

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
   <style type="text/css">
       html, body
       {
           font-family: Verdana;
           font-weight: 10px;
       }
       .alert
       {
           color: Red;
       }
   </style>
   <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.4.min.js" type="text/javascript"></script>
   <script language="javascript" type="text/javascript">
       $(document).ready(function () {
           var AllowedExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
           $("#<%=FileUpload1.ClientID %>").change(function () {
               if ($.inArray($(this).val().split('.').pop().toLowerCase(), AllowedExtension) == -1) {
                   $("#<%=msg.ClientID %>").text("Only \'jpeg\', \'jpg\', \'png\', \'gif\', \'bmp\' are allowed.");
               } else {
                   $("#<%=msg.ClientID %>").text("");
               }
           });
       });
   </script>
</head>
<body>
   <form id="form1" runat="server">
   <div>
       <h2>Validate File Upload using jQuery in asp.net File Upload Control</h2>
       <asp:FileUpload ID="FileUpload1" runat="server" />
       <asp:Label ID="msg" runat="server" Text="" CssClass="alert"></asp:Label>
   </div>
   </form>
</body>
</html>

Hope this helps

Good Luck

Categories: ASP.Net, Jquery

Display an image instead of Checkbox in GridView

September 9, 2011 1 comment

Hi all,

try this example to Display an image instead of checkbox in GridView

<asp:TemplateField>
 <ItemTemplate>
  <asp:Image runat="Server" ImageUrl='<%# Convert.ToBoolean(Eval("bitField")) ? "~/images/trueImage.jpg" : "~/images/falseImage.jpg"%>'
 </ItemTemplate>
</asp:TemplateField>

Hope this helps

Good Luck

Categories: ASP.Net

Using Custom Validator Control to Compare two Dates

September 8, 2011 6 comments

Hi all,

try this example to Use Custom Validator Control to Compare two Dates using Client Side :-

The Javascript function :-

<script type="text/javascript">
function fncClientCheckDate(sender, args) {
if (new Date(document.getElementById("textBox1").value) > new Date(document.getElementById("textBox2").value))
{
args.IsValid = false;
return;
}
args.IsValid = true;
}
</script>

the Design should be :-

Start Date :-
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="textBox1_CalendarExtender" runat="server"
Enabled="True" TargetControlID="textBox1">
</cc1:CalendarExtender>
<br />
End Date :-
<asp:TextBox ID="textBox2" runat="server"></asp:TextBox>
<cc1:CalendarExtender ID="textBox2_CalendarExtender" runat="server"
Enabled="True" TargetControlID="textBox2" >
</cc1:CalendarExtender>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="End Date should be greater than Start Date" ClientValidationFunction="fncClientCheckDate"></asp:CustomValidator>

Hope this helps

Good Luck

Categories: ASP.Net, Javascript

Use The NOT IN clause in LINQ to SQL

September 8, 2011 Leave a comment

Hi all,

try this example to use the NOT IN clause in LINQ to SQL

This is one SQL query that returns that value.

SELECT * FROM [dbo].[Customers] AS c
WHERE c.[CustomerID] NOT IN (
SELECT o.[CustomerID]
FROM [dbo].[Orders] AS o
)

LINQ offers a Contains extension method that allows writing the following code.

NorthwindDataContext dbml = new NorthwindDataContext();
dc.Log = Console.Out;
var query =
from c in dbml.Customers
where !(from o in dbml.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
foreach (var c in query) Console.WriteLine( c );

Hope this helps

Good Luck

Categories: ASP.Net, Linq

Implement Key Value Pair with jQuery Autocomplete Plugin in ASP.Net

September 3, 2011 4 comments

Hi all,

try this example to Implement Key Value Pair with jQuery Autocomplete Plugin in ASP.Net

In this example i will use Customer Table in Northwind Database

1) Open VS2008 and create a new web site

2) Add new Web.Config file and inside it i will add the connection string to Northwind database

<connectionStrings>
  <add name="constr" connectionString="Data Source = .;Initial Catalog = Northwind; Integrated Security = true"/>
 </connectionStrings>

3) Add Web Service and name it “Service.asmx” and in Service.cs add this code :-


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Script.Services;

/// <summary>
/// Summary description for Service_CS
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService {

    public Service () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public string[] GetCustomers(string prefix)
    {
        List<string> customers = new List<string>();
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager
                    .ConnectionStrings["constr"].ConnectionString;
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.CommandText = "select ContactName, CustomerId from Customers where " +
                "ContactName like @SearchText + '%'";
                cmd.Parameters.AddWithValue("@SearchText", prefix);
                cmd.Connection = conn;
                conn.Open();
                using (SqlDataReader sdr = cmd.ExecuteReader())
                {
                    while (sdr.Read())
                    {
                        customers.Add(string.Format("{0}-{1}", sdr["ContactName"], sdr["CustomerId"]));
                    }
                }
                conn.Close();
            }
            return customers.ToArray();
        }
    }
}

4) Add new Web page and name it “Default.aspx”


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"
type = "text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
type = "text/javascript"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css"
rel = "Stylesheet" type="text/css" />
<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=txtSearch.ClientID %>").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
                    data: "{ 'prefix': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                            return {
                                label: item.split('-')[0],
                                val: item.split('-')[1]
                            }
                        }))
                    },
                    error: function (response) {
                        alert(response.responseText);
                    },
                    failure: function (response) {
                        alert(response.responseText);
                    }
                });
            },
            select: function (e, i) {
                $("#<%=hfCustomerId.ClientID %>").val(i.item.val);
            },
            minLength: 1
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txtSearch" runat="server"></asp:TextBox>
    <asp:HiddenField ID="hfCustomerId" runat="server" />
    <br />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick = "Submit" />
    </form>
</body>
</html>

and in code behind add this code :-

protected void Submit(object sender, EventArgs e)
    {
        string customerName = Request.Form[txtSearch.UniqueID];
        string customerId = Request.Form[hfCustomerId.UniqueID];
        Response.Write("Customer Name :- " + customerName + " and ID :- " + customerId);
    }

Hope this helps

Good Luck

Categories: ASP.Net, Jquery