Navigation

Search

Categories

On this page

jQuery: Check/uncheck all checkboxes with specific value
How to Delete Multiple Rows in a Gridview
Check/Uncheck All Checkboxes in a GridView
Getting ID of the newly inserted record in SQL Server Database using ADO.Net
Accessing Controls Using Javascript
ASP.NET IP Geolocation Tracker

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 240
This Year: 46
This Month: 3
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Tuesday, June 30, 2009
Tuesday, June 30, 2009 6:02:23 PM (GMT Daylight Time, UTC+01:00) ( jQuery )

I was working on something that required to me to check all checkboxes in a form.  It’s pretty easy to toggle back and forth using jQuery using something like this:

<script type="text/javascript">
    // main check all checkbox
    $(document).ready(function() {            
            $('#chkAll').click(
             function() {                
                $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
            });     
         });
</script>
<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="" />
<input type="checkbox" name="b" value="2" id="" />
<input type="checkbox" name="c" value="3" id="" />
<input type="checkbox" name="d" value="4" id="" />
<input type="checkbox" name="e" value="5" id="" />
<input type="checkbox" name="f" value="5" id="" />
</form>

However, I also needed something where I wanted checkboxes checked only when their values equaled something specific.  In this case, only checkboxes with a value of 9 will get checked.

<script language="Javascript" type="text/javascript">
$(document).ready(function() {
   $("#chkAll").click(function(event){
      $('input[@type=checkbox]').each( function() {
        if($(this).val()==5)
          this.checked = !this.checked;
      });
   });
});
</script> 

<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="" />
<input type="checkbox" name="b" value="2" id="" />
<input type="checkbox" name="c" value="3" id="" />
<input type="checkbox" name="d" value="4" id="" />
<input type="checkbox" name="e" value="9" id="" />
<input type="checkbox" name="f" value="9" id="" />
</form>

You could also do something like where only checkboxes with an id that begins with “chkEvent” get checked using the “BeginsWith” function ^.

<script language="Javascript" type="text/javascript">
    $(document).ready(function() {
    $("#chkAll").click(
        function() {
                $("INPUT[id^='chkEvent']").attr('checked', $('#chkAll').is(':checked'));
            });
        });   
</script> 




<form method="post" action="">
<input name="chkAll" id="chkAll" type="checkbox" />
<input type="checkbox" name="a" value="1" id="chkEventA" />
<input type="checkbox" name="b" value="2" id="chkEventB" />
<input type="checkbox" name="c" value="3" id="chkEventC" />
<input type="checkbox" name="d" value="4" id="chkEventD" />
<input type="checkbox" name="e" value="9" id="chkEventE" />
<input type="checkbox" name="f" value="9" id="chkEventF" />
</form>
Comments [0] | | # 
# Wednesday, June 24, 2009
Wednesday, June 24, 2009 2:42:26 PM (GMT Daylight Time, UTC+01:00) ( Gridview )


The Gridview provides built-in functionality for deleting rows in a Gridview one at a time but deleting multiple records in batches is usually more efficient.

First create a SqlDataSource and bind the Gridview to it:

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
    SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
    DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
    ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
       <DeleteParameters>
           <asp:Parameter Name="EmployeeID" />
       </DeleteParameters>
</asp:SqlDataSource>

Create a template field inside of the <Columns> of the Gridview:

<asp:TemplateField>
       <ItemTemplate>
             <asp:CheckBox ID="chkRows" runat="server"/>
      </ItemTemplate>
</asp:TemplateField>

The code should now look similar to this.  Notice that the DataKeyNames property is EmployeeID for the Gridview.

<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
   <DeleteParameters>
       <asp:Parameter Name="EmployeeID" />
   </DeleteParameters>
</asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
   
   <Columns>
      <asp:TemplateField>
          <ItemTemplate>
            <asp:CheckBox ID="cbRows" runat="server"/>
          </ItemTemplate>
       </asp:TemplateField>
 
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
   </Columns>
</asp:GridView>
  
<asp:Button
   ID="btnMultipleRowDelete"
   OnClick="btnMultipleRowDelete_Click"
   runat="server"
   Text="Delete Rows" />

Here’s the code which performs the actual deleting of the records:

Protected Sub btnMultipleRowDelete_Click(ByVal sender As Object, ByVal e As EventArgs)
' Looping through all the rows in the GridView
For Each row As GridViewRow In GridView1.Rows
Dim checkbox As CheckBox = CType(row.FindControl("cbRows"), CheckBox) 

'Check if the checkbox is checked. 
If checkbox.Checked Then

'Retreive the Employee ID
Dim employeeID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)
'Pass the value of the selected Employee ID to the Delete command.
SqlDataSource1.DeleteParameters("EmployeeID").DefaultValue = employeeID.ToString()
SqlDataSource1.Delete()
End If
Next row
End Sub

Comments [0] | | # 
Wednesday, June 24, 2009 2:25:09 PM (GMT Daylight Time, UTC+01:00) ( )


Awhile ago, I created an example of how to do this server-side.  This example is probably more effective in most cases since it’s done client-side using javascript.

<script language="javascript">

 function SelectAllCheckboxes(spanChk){

   var oItem = spanChk.children;
   var theBox= (spanChk.type=="checkbox") ? 
        spanChk : spanChk.children.item[0];
   xState=theBox.checked;
   elm=theBox.form.elements;

   for(i=0;i<elm.length;i++)
     if(elm[i].type=="checkbox" && 
              elm[i].id!=theBox.id)
     {
       if(elm[i].checked!=xState)
         elm[i].click();
     }     
 }
</script>
<Columns>                
<asp:TemplateField HeaderText="">    
<HeaderTemplate>
    <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" runat="server" type="checkbox" />
</HeaderTemplate>                               
<ItemTemplate>
     <asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>            
</asp:TemplateField>
……
</Columns>
Comments [0] | | # 
# Monday, June 15, 2009
# Wednesday, June 03, 2009
Wednesday, June 03, 2009 10:16:30 PM (GMT Daylight Time, UTC+01:00) ( Javascript/AJAX )

 

You can get the values for form controls on the client side using javascript using a method like this:

var label = document.getElementById("<%=Label1.ClientID%>"); 

If the control is inside another control like a FormView or a GridView then you can use this method:

var label = document.getElementById('<%= FormView1.FindControl("Label1").ClientID %>');
Comments [0] | | # 
# Tuesday, June 02, 2009
Tuesday, June 02, 2009 5:40:12 PM (GMT Daylight Time, UTC+01:00) ( ASP.NET )


Here is a working example.

There are a lot of paid as well as free services that can find Visitor Geographical information like country, region, city, latitude, longitude, ZIP code, time zone etc from I.P Addresses. http://iplocationtools.com/ip_location_api.php is one such free IP Geolocation API that returns geographical data in three formats: XML, JSON and CSV. In this article, we will consume this API and fetch visitor geographical information in XML format in the simplest possible way, using LINQ To XML.

Using the IP Address Location XML API is easy. Just specify the I.P. address as shown below http://iplocationtools.com/ip_query2.php?ip=74.125.45.100 and you will receive an XML document with the visitor geographical information in the following format:

<Locations>
 <Location id="0"> 
    <Ip>74.125.45.100</Ip> 
    <Status>OK</Status> 
    <CountryCode>US</CountryCode> 
    <CountryName>United States</CountryName> 
    <RegionCode>06</RegionCode> 
    <RegionName>California</RegionName> 
    <City>Mountain View</City> 
    <ZipPostalCode>94043</ZipPostalCode> 
    <Latitude>37.4192</Latitude> 
    <Longitude>-122.057</Longitude> 
 </Location> 
</Locations>

In order to specify multiple I.P(maximum 25), use a comma(,) separator as shown here: http://iplocationtools.com/ip_query2_country.php?ip=74.125.45.100,206.190.60.37

We will use the XDocument class to consume the XML API in just two lines of code.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Xml.Linq" %>

<script runat="server">

Protected Sub btnGetLoc_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnGetLoc.Click
        Dim url As String = String.Empty

        If txtIP.Text.Trim() <> String.Empty Then
            url = String.Format("http://iplocationtools.com/ip_query2.php?ip={0}", txtIP.Text.Trim())
            Dim xDoc As XDocument = XDocument.Load(url)
            
            If xDoc Is Nothing Or xDoc.Root Is Nothing Then
                Throw New ApplicationException("Data is not Valid")
            End If

            Xml1.TransformSource = "IP.xslt"
            Xml1.DocumentContent = xDoc.ToString()
        End If
End Sub

</script>

<!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 id="Head1" runat="server">
    <title>IP Address Location</title>
    <style type="text/css">
        body
        {
            font: normal 11px auto "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;    
            background-color: #ffffff;
            color: #4f6b72;       
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Panel ID="panelLoc" runat="server">
                    <asp:TextBox ID="txtIP" runat="server"></asp:TextBox>
                        <asp:Button ID="btnGetLoc" runat="server" Text="Get IP Details" />
                    <br />
                    <asp:Xml ID="Xml1" runat="server"></asp:Xml>
                </asp:Panel>
            </ContentTemplate>
        </asp:UpdatePanel>
        
        <asp:UpdateProgress ID="updProgress" AssociatedUpdatePanelID="UpdatePanel1" runat="server">
            <ProgressTemplate><img alt="progress" src="/images/progress.gif"/> </ProgressTemplate>
        </asp:UpdateProgress>

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

Our XSLT (IP.xslt) will look similar to the following:

<?xmlversion='1.0'?>
<xsl:stylesheetxmlns:xsl="http://www.w3.org/1999/XSL/Transform"version="1.0">
 <xsl:templatematch="/">
    <HTML>
      <BODY>
        <TABLEcellspacing="3"cellpadding="8">
          <TR>
            <TDclass="heading">
              <B>Ip</B>
            </TD>
            <TDclass="heading">
              <B>Status</B>
            </TD>
            <TDclass="heading">
              <B>CountryCode</B>
            </TD>
            <TDclass="heading">
              <B>CountryName</B>
            </TD>
            <TDclass="heading">
              <B>RegionCode</B>
            </TD>
            <TDclass="heading">
              <B>RegionName</B>
            </TD>
            <TDclass="heading">
              <B>City</B>
            </TD>
            <TDclass="heading">
              <B>ZipPostalCode</B>
            </TD>
            <TDclass="heading">
              <B>Latitude</B>
            </TD>
            <TDclass="heading">
              <B>Longitude</B>
            </TD>
          </TR>
          <xsl:for-eachselect="Locations/Location">
            <TRbgcolor="#C1DAD7">
              <TDwidth="5%"valign="top">
                <xsl:value-ofselect="Ip"/>
              </TD>
              <TDwidth="5%"valign="top">
                <xsl:value-ofselect="Status"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="CountryCode"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="CountryName"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="RegionCode"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="RegionName"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="City"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="ZipPostalCode"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="Latitude"/>
              </TD>
              <TDwidth="10%"valign="top">
                <xsl:value-ofselect="Longitude"/>
              </TD>
            </TR>
          </xsl:for-each>
        </TABLE>
      </BODY>
    </HTML>
 </xsl:template>
</xsl:stylesheet>

Comments [0] | | #