Navigation

Search

Categories

On this page

Using jQuery to Change the Background Color of Rows on Hover
Check/Uncheck all Items in an ASP.NET CheckBox List using jQuery
Using the jQuery $.get function
jQuery Form Plugin
Using a DbTransaction object to add transaction context with the SqlDataSource control to update data

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: 378
This Year: 6
This Month: 1
This Week: 0
Comments: 17

Sign In
Pick a theme:

# Wednesday, December 31, 2008
Wednesday, December 31, 2008 3:47:52 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

Another example of how cool jQuery is.

Here is a working example

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then       
            BindGridView()
        End If

    End Sub
    
    Sub BindGridView()
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies"

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub   
           
</script>

<html>
<head><title></title>
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>

    <script type="text/javascript">         
         $(document).ready(function() {        
            $("#dgMovies tr").css({ background: "F7F6F3" }).hover(
                function() { $(this).css({ background: "#C1DAD7" }); },
                function() { $(this).css({ background: "#F7F6F3" }); }
                );
        });
    </script>
    
</head>
<body>

<form runat="server">

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="false" 
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="Blue" Font-Bold="True" ForeColor="Black" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

</form>

</body>
</html>
Comments [0] | | # 
Wednesday, December 31, 2008 3:21:57 AM (GMT Standard Time, UTC+00:00) ( Javascript/AJAX | jQuery )

There are many ways to check/uncheck a list of checkboxes using javascript or even in ASP.NET such as in a Gridview.  Using jQuery is probably one of the easiest and most elegant solutions I've found.  Here is an example of how to do it.

<%@ Page Language="VB" %>

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

<script runat="server">
    
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
        If (Not Page.IsPostBack) Then
            cb1.Items.Add(New ListItem("Items 1", "Items 1"))
            cb1.Items.Add(New ListItem("Items 2", "Items 2"))
            cb1.Items.Add(New ListItem("Items 3", "Items 3"))
            cb1.Items.Add(New ListItem("Items 4", "Items 4"))
            cb1.Items.Add(New ListItem("Items 5", "Items 5"))
        End If
    End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.2.6.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    $(document).ready(function() {
            $('#chkAll').click(
             function() {
                 $("INPUT[type='checkbox']").attr('checked', $('#chkAll').is(':checked'));
             });
         });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBox ID="chkAll" runat="server" Text="Check All" /><br />
        <asp:CheckBoxList ID="cb1" runat="server">
        </asp:CheckBoxList>
    </div>
    </form>
</body>
</html>

Here is another example which I think is a little simpler than the one above

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Access Values From Multiple or Selected ASP.NET TextBoxes</title>

<script src="http://ajax.Microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>

<script type="text/javascript">
$(function() {
    var $chkBox = $("input:checkbox[id$=chkAll]");
    var $tblChkBox = $("table.chk input:checkbox");
        
        $chkBox.click(function() {
            $tblChkBox
            .attr('checked', $chkBox
            .is(':checked'));
        });
        
        // Unchecks chkAll when a checked CheckBox in cbList is unchecked
        
        $tblChkBox.click(
        function(e) {
            if (!$(this)[0].checked) {
            $chkBox.attr("checked", false);
        }
    });
});
</script>
</head>
<body>
<form id="form1" runat="server">

<asp:CheckBox ID="chkAll" runat="server" Text="Check All" ToolTip="Click here to check/uncheck all checkboxes at once"/>
<br /><hr />
    <asp:CheckBoxList ID="cbList" runat="server" class="chk">
        <asp:ListItem Text="Option A" Value="A" />
        <asp:ListItem Text="Option B" Value="B" />
        <asp:ListItem Text="Option C" Value="C" />
        <asp:ListItem Text="Option D" Value="D" />
        <asp:ListItem Text="Option E" Value="E" />
    </asp:CheckBoxList>
<br />

</form>
</body>
</html>
Comments [0] | | # 
# Friday, December 19, 2008
Friday, December 19, 2008 2:49:37 AM (GMT Standard Time, UTC+00:00) ( )

I've been using jQuery a whopping 2 days now and I'm already amazed at how powerful it is.  Using the jQuery .get() method, making AJAX calls to another page a snap.

Below are 2 examples of essential the same thing.  The addNumbers_Click function just passes 2 integers to jQuery.giveMeSomething.aspx, adds the 2 values and returns the total back to this page to be displayed in the "results" div.  Notice in the $.get() function that the first parameter is the URL to send the values to followed by the values to send in the URL string. Note that it doesn't use the typical page.aspx?value=somevalue constructor and takes are of all of that for you.

The second exampe, searchMovies_Click, does the same thing except passes a movie title to jQuery.contact.form.response.gridview.aspx, looks up matching movie titles in the database and returns the results in a gridview.  Now that's cool!  

Here is a working demo

 

<script type="text/javascript">     
        function addNumbers_Click() {
        var number1 = $('#number1').attr('value');
        var number2 = $('#number2').attr('value');
        $.get('jQuery.giveMeSomething.aspx', {number1: number1, number2: number2},
        function(data) {
              $('#results').empty().html(data);   
              // This is just another way of doing the same as the line above
// $("#results").empty().append(data);
}); } function searchMovies_Click() { var movietitle = $('#movietitle').attr('value'); $.get('jQuery.contact.form.response.gridview.aspx', {title: movietitle}, function(data) { $('#movieResults').empty().html(data); }); } </script> <body> <input type="text" id="number1" value="0" /> + <input type="text" id="number2" value="0" /> <input type="button" onclick="addNumbers_Click();" value="Add Numbers" /> <div id="results"></div> <p /> <input type="text" id="movietitle" /> <input type="button" onclick="searchMovies_Click();" value="Search Movies" /> <div id="movieResults"></div> <p /> </body>

** jQuery.giveMeSomething.aspx **

<%@ Page Language="VB" %>

<script runat="server">
    Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim intNumber1 As Integer = Request("number2")
        Dim intNumber2 As Integer = Request("number1")
        Response.Write("The answer is " & intNumber1 + intNumber2 & ". <b>Thanks for playing </b>")
    End Sub
</script>

** 'jQuery.contact.form.response.gridview.aspx **

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then
            Dim strTitle As String = Request("title")
            lblTitle.Text = strTitle
        
            BindGridView(strTitle, "Title")
        End If

    End Sub
    
    Sub BindGridView(ByVal strTitle As String, ByVal strSortOrder As String)
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies WHERE Title LIKE '%" & strTitle & "%' ORDER BY " & strSortOrder

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub
    
    Sub SortGridView(ByVal Sender As Object, ByVal e As GridViewSortEventArgs)
        BindGridView(lblTitle.Text, e.SortExpression.ToString())
    End Sub
       
</script>

<html>
<head><title></title>
</head>
<body>

<form runat="server">

<asp:gridview runat="server" CellPadding="4" 
ForeColor="#333333" GridLines="None" 
AllowSorting="true" OnSorting="SortGridView"
id="dgMovies" Width="80%" 
HorizontalAlign="Center" 
Font-Names="Tahoma" 
Font-Size="Small" 
EmptyDataText="No records were found">
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />    
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:gridview>

<asp:Label ID="lblTitle" runat="server" Visible="false" />

</form>

</body>
</html>
Comments [0] | | # 
# Tuesday, December 16, 2008
Tuesday, December 16, 2008 4:00:19 PM (GMT Standard Time, UTC+00:00) ( )

I've been learning jQuery the last few days and I've been experimenting with an amazing plugin called jQuery Form Plugin.   This jQuery plugin makes it incredibly easy to add AJAX-style effects to forms to your applications. This example uses a simple form to search a movies database by title, but you can see how easy it is to expand this and create a powerful data-driven AJAX application.

Here is a working demo.

** jQuery.Contact.Form.aspx **

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Form</title>

<!--Import both the jQuery and jQuery form libraries -->
<script type="text/javascript" src="jquery/jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="jquery/jquery.form.js"></script>

<script type="text/javascript">

// prepare the form when the DOM is ready 
$(document).ready(function() { 
    // bind form using ajaxForm 
    $('#htmlForm').ajaxForm({ 
        // target identifies the element(s) to update with the server response 
        target: '#htmlExampleTarget', 
 
        // success identifies the function to invoke when the server response 
        // has been received; here we apply a fade-in effect to the new content 
        success: function() { 
            $('#htmlExampleTarget').fadeIn('5000'); 
        } 
    }); 
});

</script>
</head>

<body>
<form id="htmlForm" action="jquery.contact.form.response.aspx" method="post"> 
    Movie Search: <input type="text" name="title" value="Truth" /> 
    <input type="submit" value="Search Movies" /> 
</form>
Suggestions: "truth","attack","an","space"<br /><br />

<div id="htmlExampleTarget"></div>

</body>
</html>

This is the page that the above page posts to, jquery.contact.form.response.aspx.   We pass the movie title from the search form on the first page and use it to search the Movies database by Title.  We create a datareader with the results and use them to create a string with the StringBuilder method inside a styled div to be placed inside the div with an id of htmlExampleTarget.

<%@ Page Language="VB" %>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>

<script runat="server">
    Sub Page_Load()
        
           Dim strTitle As String = Request.Form("title")
           
           Dim con as New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
           Dim strSqlText As String = "SELECT Title, Director FROM Movies WHERE Title LIKE '%" & strTitle & "%'" 

           Dim cmd as New SqlCommand(strSQLText)
           con.Open()
           cmd.Connection = con
                     
           Dim dr As SqlDataReader = cmd.ExecuteReader()           
           
           Dim sb As New System.Text.StringBuilder("<div style=""background-color:#ffa; padding:20px"">")

           While (dr.Read())             
              sb.Append(dr("Title") & ", Director: " & dr("Director") & "<br />") 
           End While
           
           dr.Close()          
                  
           sb.Append("</div>")       
           Response.Write((sb).ToString())    
           
           con.Close()
           con.Dispose() 
      
    End Sub
</script>

You can also pass an entire Gridview through the AJAX call.

Here is a working demo.

<script runat="server">
    Sub Page_Load()

        If Not Page.IsPostBack Then
            Dim strTitle As String = Request.Form("title")
            lblTitle.Text = strTitle
        
            BindGridView(strTitle, "Title")
        End If

    End Sub
    
    Sub BindGridView(ByVal strTitle As String, ByVal strSortOrder As String)
        
        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString)
        Dim strSqlText As String = "SELECT Title, Director FROM Movies WHERE Title LIKE '%" & strTitle & "%' ORDER BY " & strSortOrder

        Dim cmd As New SqlCommand(strSqlText)
        con.Open()
        cmd.Connection = con

        dgMovies.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection)
        dgMovies.DataBind()

        con.Close()
        con.Dispose()
        
    End Sub
    
    Sub SortGridView(ByVal Sender As Object, ByVal e As GridViewSortEventArgs)
        BindGridView(lblTitle.Text, e.SortExpression.ToString())
    End Sub
       
</script>
Comments [0] | | # 
# Friday, December 12, 2008
Friday, December 12, 2008 8:18:44 PM (GMT Standard Time, UTC+00:00) ( ASP.NET | SQL )


This example shows how you can use a DbTransaction object to add transaction context when using the SqlDataSource control to update data.

<%@Page  Language="VB" %>
<%@Import Namespace="System.Data" %>
<%@Import Namespace="System.Data.Common" %>
<%@Import Namespace="System.Diagnostics" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

 Sub On_Click(ByVal source As Object, ByVal e As EventArgs)
        SqlDataSource1.Update()
 End Sub 'On_Click

 Sub On_Sql_Updating(ByVal source As Object, ByVal e As SqlDataSourceCommandEventArgs)
     Dim command as DbCommand
     Dim connection as DbConnection
     Dim transaction as DbTransaction

     command = e.Command
     connection = command.Connection     
     connection.Open()     
     transaction = connection.BeginTransaction()
     command.Transaction = transaction

 End Sub 'On_Sql_Updating

 Sub On_Sql_Updated(ByVal source As Object, ByVal e As SqlDataSourceStatusEventArgs)

    Dim command As DbCommand
    Dim transaction As DbTransaction

    command = e.Command
    transaction = command.Transaction

    ' We must succeed for the data change to be committed. For 
    ' simplicity, we set this value to true. 
    Dim OtherProcessSucceeded as Boolean = True

    If (OtherProcessSucceeded) Then
        transaction.Commit()
        Label2.Text="The record was updated successfully!"
    Else    
        transaction.Rollback()
        Label2.Text="The record was not updated."
    End If
    End Sub 'On_Sql_Updated
</script>

<html  >
  <head id="Head1" runat="server">
    <title>Command Transaction</title>
</head>
<body>
    <form id="form1" runat="server">
      <asp:SqlDataSource
          id="SqlDataSource1"
          runat="server"
          ConnectionString="<%$ ConnectionStrings:MyDatabase%>"
          SelectCommand="SELECT ID, Title, Director FROM Movies"
          UpdateCommand="UPDATE Movies SET Title=@Title WHERE ID=@ID"
          OnUpdating="On_Sql_Updating"
          OnUpdated ="On_Sql_Updated">
          <UpdateParameters>
              <asp:ControlParameter Name="Title" ControlId="TextBox1" PropertyName="Text" />
              <asp:ControlParameter Name="ID" ControlId="DropDownList1" PropertyName="SelectedValue" />
          </UpdateParameters>
      </asp:SqlDataSource>

      <asp:DropDownList
          id="DropDownList1"
          runat="server"
          DataTextField="Title"
          DataValueField="ID"
          DataSourceID="SqlDataSource1">
      </asp:DropDownList>

      <br /><br />
      <asp:Label id="Label1" runat="server" Text="Enter a new movie title." AssociatedControlID="TextBox1" />
      <asp:TextBox id="TextBox1" runat="server" />
      <asp:Button id="Submit" runat="server" Text="Submit" OnClick="On_Click" />

      <br /><asp:Label id="Label2" runat="server" Text="" />

    </form>
  </body>
</html>
Comments [0] | | #