Navigation

Search

Categories

On this page

ASP.NET 4.0 and the Entity Framework – Gridview
LINQ to SQL Samples In VB.NET
Find the Nth Maximum and Minimum Value in a Column
Count the number of rows in every table in a database
Convert Date to String in SQL Server
Using jQuery to Create an Image Slideshow
Using jQuery to Restrict Textbox Content to Alphabetic Characters
Clicking a Gridview to Get the Cell Contents Using jQuery
How to generate a random password
T-SQL Examples
Using the jQuery Tablesorter with ASP.NET

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: 245
This Year: 51
This Month: 0
This Week: 0
Comments: 0

Sign In
Pick a theme:

# Wednesday, June 16, 2010
Wednesday, June 16, 2010 4:15:23 PM (GMT Daylight Time, UTC+01:00) ( Entity Framework | Gridview )


This article demonstrates how to view and edit records in a table using the GridView, EntityDataSource, and Validator controls.  The article also demonstrates how to generate an ADO.NET Entity Data Model to update and delete records in a table.

Comments [0] | | # 
# Monday, June 14, 2010
Monday, June 14, 2010 9:27:21 PM (GMT Daylight Time, UTC+01:00) ( LINQ | VB.NET )


I’m trying to learn LINQ and came across this page of useful examples in VB

http://msdn.microsoft.com/en-us/vbasic/bb688085.aspx

Comments [0] | | # 
# Thursday, June 03, 2010
Thursday, June 03, 2010 9:25:16 PM (GMT Daylight Time, UTC+01:00) ( SQL )

Here’s a simple query to find the Nth Maximum and Minimum values in a SQL Server table column using the Row_Number() function. We will find the 2nd highest and 3rd lowest values in the column.

DECLARE @tmp TABLE(id integer, amount integer)
INSERT INTO @tmp values(4, 9543)
INSERT INTO @tmp values(6, 34)
INSERT INTO @tmp values(3, 54)
INSERT INTO @tmp values(2, 6632)
INSERT INTO @tmp values(5, 645)
INSERT INTO @tmp values(1, 1115)
INSERT INTO @tmp values(7, 345)

-- FIND Nth Maximum value
SELECT id, amount
FROM(SELECT id, amount, Row_Number() OVER(ORDER BY amount DESC) AS highest FROM @tmp) as x
WHERE highest = 2
-- FIND Nth Minimum value
SELECT id, amount
FROM(SELECT id, amount, Row_Number() OVER(ORDER BY amount ASC) AS lowest FROM @tmp) as x
WHERE lowest = 3
image 
Comments [0] | | # 
Thursday, June 03, 2010 8:35:43 PM (GMT Daylight Time, UTC+01:00) ( SQL )


To get an accurate value of all the rows in a SQL Server table, use DBCC UPDATEUSAGE. Here’s a query that first uses DBCC UPDATEUSAGE and then count all the rows in all the tables of a database using the undocumented stored procedure sp_msForEachTable.

DECLARE @DynSQL NVARCHAR(255) 
SET @DynSQL = 'DBCC UPDATEUSAGE (' + DB_NAME() + ')' 
EXEC(@DynSQL) 
EXEC sp_msForEachTable'SELECT PARSENAME(''?'', 1) as TableName,COUNT(*) as NumberOfRows FROM ?'

image

Comments [0] | | # 
Thursday, June 03, 2010 8:25:37 PM (GMT Daylight Time, UTC+01:00) ( SQL )


Here’s a query that converts a Date to a String in SQL Server:

DECLARE @Dt as DateTime
SET @Dt = '2010-02-22 11:45:17' SELECT CONVERT(CHAR(8), @Dt, 112)+ REPLACE(CONVERT(CHAR(8), @Dt, 114), ':', '')

In the query shown above, the style value 112 gives an output of yymmdd and a style value 114, gives an output of hh:mi:ss:mmm(24h). To display the milliseconds too, change Char(8) to Char(12).

image

Comments [0] | | # 
Thursday, June 03, 2010 7:22:31 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo of this code.

<%@ Page Language="VB" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Image Slideshow</title>

<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    var imgs = [
    '../images/1.jpg',
    '../images/2.jpg',
    '../images/3.jpg',
    '../images/4.jpg'];
    var cnt = imgs.length;
    var $imageSlide = $('img[id$=imageSlide]');
    // set the image control to the last image
    $imageSlide.attr('src', imgs[cnt - 1]);
    setInterval(Slider, 4000);
    function Slider() {
        $imageSlide.fadeOut("slow", function () {
        $(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
     });
    }
});
</script>

</head>


<body>
<form runat="server" id="form1">

<div class="smallDiv">
<h2>Image Slide Show - Image Changes Every 4 Seconds</h2><br />
<asp:Image ID="imageSlide" runat="server" class="imgdiv" />
</div>

</form>

</body>
</html>
Comments [0] | | # 
Thursday, June 03, 2010 7:11:48 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo of this example.

<%@ Page Language="VB" %>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Alpha Characters Only</title>


<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function () {
        $(".gv input.rate").bind('keyup blur', function (e) {
            if (this.value.match(/[^a-zA-Z ]/g)) {
                this.value = this.value.replace(/[^a-zA-Z ]/g, '');
            }
        });
    });
</script>
</head>

<body>
<form runat="server" id="form1">

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />


        <h3>Using a Gridview</h3>
<div class="tableDiv">
        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id" 
        AutoGenerateColumns="false"
        Runat="server" class="gv">

        <Columns>
        
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Title" HeaderText="Title" />
        <asp:TemplateField HeaderText="Comments">
        <ItemTemplate>
            <asp:TextBox id="txtComments" runat="server" MaxLength="25" class="rate" />
        </ItemTemplate>
        </asp:TemplateField>
        </Columns>
        </asp:GridView>
        <p id="para"></p>
</div>
</form>

</body>
</html>
Comments [0] | | # 
Thursday, June 03, 2010 5:51:24 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Here is a working demo on how this works.

<%@ 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">

    Sub grdMovies_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        If grdMovies.Rows.Count > 0 Then
            grdMovies.UseAccessibleHeader = True
            'Adding the <thead> and <tbody> elements   
            grdMovies.HeaderRow.TableSection = TableRowSection.TableHeader
        End If
    End Sub
</script>
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Gridview Cell Contents</title>

<style type="text/css">
.highlite
{
    background-color:Gray;
}
</style>
<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    $(".gv > tbody > tr:not(:has(table, th))")
        .css("cursor", "pointer")
            .click(function(e) {
                $(".gv td").removeClass("highlite");
                var $cell = $(e.target).closest("td");
                $cell.addClass('highlite');
                var $currentCellText = $cell.text();
                var $leftCellText = $cell.prev().text();
                var $rightCellText = $cell.next().text();
                var $colIndex = $cell.parent().children().index($cell);
                var $colName = $cell.closest("table").find('th:eq(' + $colIndex + ')').text();
                $("#para").empty().append("<b>Current Cell Text: </b>"+ $currentCellText + "<br/>")
                .append("<b>Text to Left of Clicked Cell: </b>"+ $leftCellText + "<br/>")
                .append("<b>Text to Right of Clicked Cell: </b>" + $rightCellText + "<br/>")
                .append("<b>Column Name of Clicked Cell: </b>" + $colName)
            });
        });
</script>

</head>


<body>
<form runat="server" id="form1">

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:MyDatabase %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />


        <h3>Using a Gridview</h3>
<div class="tableDiv">
        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        OnPreRender="grdMovies_PreRender"
        Runat="server" class="gv" />

        <p id="para"></p>
</div>
</form>

</body>
</html>

We want to select only those rows which are inside the TBODY:

$(".gv > tbody > tr:not(:has(table, th))") 

We have used ‘e.target’ to find out the element that was clicked. This object is cached in the ‘cell’ variable:

var $cell = $(e.target).closest("td"); 

The closest() as given in the jQuery documentation, “works by first looking at the current element to see if it matches the specified expression, if so it just returns the element itself. If it doesn't match then it will continue to traverse up the document, parent by parent, until an element is found that matches the
specified expression.”

With the help of the ‘cell’ variable, we can use the DOM tree traversal methods like prev() and next(), to retrieve the value of the immediate ‘preceding’ and ‘following’ elements, respectively.

var $leftCellText = $cell.prev().text();
var $rightCellText = $cell.next().text(); 

Similarly the column header text is retrieved using the code shown below.

var $colIndex = $cell.parent().children().index($cell);
var $colName = $cell.closest("table").find('th:eq(' + $colIndex + ')').text(); 

As shown above, after retrieving the column index, we use the closest() method to traverse up the DOM, parent by parent until we find the table element. The Header text is then selected using:

('th:eq(' + $colIndex + ')').text()
Comments [0] | | # 
# Tuesday, June 01, 2010
Tuesday, June 01, 2010 8:52:04 PM (GMT Daylight Time, UTC+01:00) ( VB.NET )


Public Function GeneratePassword(ByVal PwdLength As Integer) As String
    Dim _allowedChars As String = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789"
    Dim rndNum As New Random()
    Dim chars(PwdLength - 1) As Char
    Dim strLength As Integer = _allowedChars.Length
    For i As Integer = 0 To PwdLength - 1
        chars(i) = _allowedChars.Chars(CInt(Fix((_allowedChars.Length) * rndNum.NextDouble())))
    Next i
    Return New String(chars)
End Function

 
Comments [0] | | # 
Tuesday, June 01, 2010 8:34:40 PM (GMT Daylight Time, UTC+01:00) ( SQL )

Here are some simple T-SQL examples  I came across that I wasn’t aware of.

Select * from tblTest Where TestName Like '[ABC]%' (Return all rows of name start with A / B / C)

Select * from tblTest Where TestName Like '[^ABC]%' (Return all rows of name not start with A and B and C)

Select *  into #test from tblTest  (Create temporary table #test and insert all records from tblTest)

Select db_name() (shows the database name which you are working on)

Select @@Servername (Shows name of the server)
Comments [0] | | # 
Tuesday, June 01, 2010 7:16:36 PM (GMT Daylight Time, UTC+01:00) ( jQuery )


Many of the data controls used by ASP.NET support built-in table sorting but they use a lot of resources.  Even using the ASP.NET AJAX controls and UpdatePanels can be a little clumsy. 

A better solution is to use the jQuery plugin tablesorter. Here are a couple of examples on how to use this plugin with both a Gridview and a Listview.

First, here is a working demo of the code below.

<%@ 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">
'By default the gridview does not include the <thead> and <tbody> tags
    Sub grdMovies_PreRender(ByVal sender As Object, ByVal e As EventArgs)
        If grdMovies.Rows.Count > 0 Then
            grdMovies.UseAccessibleHeader = True
            'Adding the <thead> and <tbody> elements   
            grdMovies.HeaderRow.TableSection = TableRowSection.TableHeader
        End If
    End Sub
</script>
    
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery Table Sorter</title>
<script src="http://code.jquery.com/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script src="jquery/jquery.tablesorter.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(function () {
        // make the Listview table sortable
        $("#moviesTable").tablesorter();

        // make the Gridview table sortable
        $("#grdMovies").tablesorter();
    });    
    </script> 
</head>


<body>
<form runat="server" id="form1">

<asp:SqlDataSource
        id="srcMovies"
        ConnectionString="<%$ ConnectionStrings:xxxxx %>"
        SelectCommand="SELECT Id,Title,Director FROM Movies"
        Runat="server" />

<h3>Using a Listview</h3>

<asp:ListView ID="lstMovies" DataSourceID="srcMovies" runat="server">
        <LayoutTemplate>
            <table id="moviesTable">
            <thead>
                <tr>
                    <th title="Sort by Id">Id</th>
                    <th title="Sort by Title">Title</th>
                    <th title="Sort by Director">Director</th>                    
                </tr>
            </thead>
            <tbody>
                    <asp:PlaceHolder ID="ItemPlaceholder" runat="server" />
            </tbody>
            </table>
        </LayoutTemplate>
        <ItemTemplate>
            <tr>
                <td><%# Eval("Id") %></td>
                <td><%# Eval("Title")%></td>
                <td><%# Eval("Director")%></td>
            </tr>
        </ItemTemplate>
        </asp:ListView>

        <h3>Using a Gridview</h3>

        <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        OnPreRender="grdMovies_PreRender"
        Runat="server" />
</form>

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