Navigation

Search

Categories

On this page

Login User Control
Check/Uncheck All Checkboxes in a GridView
User Controls
Using the Timer Control With an UpdatePanel - Part 2.
Using the Timer Control With an UpdatePanel
Adding a Custom Key/Value Pair to Web.Config - Encrypting Sections of it
Cascading Dropdown Boxes with AJAX
Getting a Record Count
Paging with LINQ to SQL
Using Different Parameter Types with the ObjectDataSource control
Using Parameters with the ObjectDataSource control
Mixing Different Languages in the App_Code Folder
Add Javascript to an ASP.NET Page
Creating User Selectable Themes
Using the Gridview.Sorting and Gridview.Sorted Events
Sharing Client-Side Code with Server-Side Code
Using Javascript with ASP.NET
Using Findcontrol
Why ASP.NET AJAX UpdatePanels are dangerous
Using a DetailsView with a Gridview control
Updating and Editing a Gridview
Connection String has not been properly iniitialized
Client Confirmation to a GridView Delete
Development Tools
Checkbox in a gridview which turns the selected row a different color when checked
Closing a OleDB Database Connection That is Locked
Using Explicit Parameters with the ObjectDataSource control
Handling Errors At the Page-Level
RegEx for validating email addresses with RegularExpressionValidator
Conditional GridView Cell Formatting
Displaying all files in a directory and in a datatable
Clearing a Form In ASP.NET
Checking for null values in Request.Querysting
The Format() Function
Formatting Dates and Times
Formatting Percentages
Formatting Numbers
Formatting Currency
Preventing Duplicate Logins
Date and time functions
Common mathematical functions
Common string functions
Removing part of a string
Assign Dataset Value to a Label Control
Document Type Declaration Error
Saving an Array to a Database
Creating an Array or String from Database Records

Archive

Blogroll

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

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 103
This Year: 41
This Month: 6
This Week: 2
Comments: 0

Sign In

 Thursday, May 22, 2008
Thursday, May 22, 2008 10:29:08 AM (Eastern Standard Time, UTC-05:00) (  |  )

This is a simple login user control used to demonstrate how to expose (get and set) the properties associated with the control. Here is a working demo.

** LoginUserControl.ascx **

<script language="VB" runat="server">

  Public BackColor As String = "white"

  Public Property Login As String
    Get
      Return txtLogin.Text
    End Get
    Set
      txtLogin.Text = Value
    End Set
  End Property

  Public Property Password As String
    Get
      Return txtPassword.Text
    End Get
    Set
      txtPassword.Text = Value
    End Set
  End Property
  
  Public Property Status As String
  Get
      Return lblStatus.Text
  End Get
  Set
      lblStatus.Text = Value
  End Set
  End Property

</script>

<table style="background-color:<%=BackColor%>;font: 10pt verdana;border-width:1;border-style:solid;border-color:black;" cellspacing=15>
  <tr>
    <td><b>Login: </b></td>
    <td><ASP:TextBox id="txtLogin" runat="server"/></td>
  </tr>
  <tr>
    <td><b>Password: </b></td>
    <td><ASP:TextBox id="txtPassword" TextMode="Password" runat="server"/></td>
  </tr>
  <tr>
    <td></td>
    <td><ASP:Button Text="Submit" runat="server"/></td>
  </tr>
  <tr>
    <td></td>
    <td><asp:Label id="lblStatus" runat="server"/></td>
  </tr>  
</table>

** LoginControl.aspx **

<%@ Register TagPrefix="MyUserControl" TagName="Login" Src="LoginUserControl.ascx" %>

<html>

<script language="VB" runat="server">
    Sub Page_Load(ByVal Sender As Object, ByVal E As EventArgs)
        If (Page.IsPostBack) Then
            MyLabel.Text &= "The UserId is " & MyLogin.Login & "<br>"
            MyLabel.Text &= "The Password is " & MyLogin.Password & "<br>"
            MyLogin.Status = "Hello world"
        End If
    End Sub
</script>

<body style="font: 10pt verdana">
  <h3>A Login User Control</h3>

  <form runat="server">
    <MyUserControl:Login id="MyLogin" UserId="John Doe" Password="Secret" BackColor="beige" runat="server"/>
  </form>
  <asp:Label id="MyLabel" runat="server"/>
</body>
</html>
 Wednesday, May 14, 2008
Wednesday, May 14, 2008 8:22:37 AM (Eastern Standard Time, UTC-05:00) (  |  )

Having the ability to check or uncheck all of the checkboxes which appear inside of a GridView is a frequent requirement.  There are several javascript libraries which will handle this on the client-side which is usually the better way to go, but this can also be done server-side and along with an AJAX UpdatePanel can be pretty elegant.  Here is a working demo.

<%@ 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 MasterCheck_Click(ByVal sender As Object, ByVal e As CommandEventArgs)
        'Enumerate each GridViewRow
        For Each gvr As GridViewRow In GridView1.Rows
            'Programmatically access the CheckBox from the TemplateField
            Dim cb As CheckBox = CType(gvr.FindControl("Checkbox1"), CheckBox)
            
            Select Case e.CommandName

                Case "Check"
                    'Check all of the checkboxes
                    cb.Checked = True
                    'Change the CommandName, CommandArgument and Text of the button
                    btnMasterCheck.CommandName = "Uncheck"
                    btnMasterCheck.CommandArgument = "Uncheck"
                    btnMasterCheck.Text = "Uncheck All"
                Case "Uncheck"
                    'Uncheck all of the checkboxes
                    cb.Checked = False
                    'Change the CommandName, CommandArgument and Text of the button
                    btnMasterCheck.CommandName = "Check"
                    btnMasterCheck.CommandArgument = "Check"
                    btnMasterCheck.Text = "Check All"
                Case Else

            End Select
        Next
    End Sub

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check/Uncheck All Checkboxes in a GridView</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:SqlDataSource
        id="srcMovies"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Title, Director FROM Movies ORDER BY Title"
        Runat="server" />
        
        <asp:ScriptManager id="sm1" runat="server" />

    <asp:UpdatePanel id="UpdatePanel1" Runat="server">
   
    <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" DataSourceID="srcMovies" AutoGenerateColumns="False">
        <Columns>
         <asp:TemplateField HeaderText="">
                 <ItemTemplate>
                    <asp:Checkbox id="Checkbox1" runat="server"  /> 
                 </ItemTemplate>
          </asp:TemplateField> 
         
         <asp:BoundField HeaderText="Title" DataField="Title" />
         <asp:BoundField HeaderText="Director" DataField="Director" />
        </Columns>
        </asp:GridView><br />
        <asp:Button ID="btnMasterCheck" runat="server" CommandName="Check" CommandArgument="Check" OnCommand="MasterCheck_Click" Text="Check All" />
    </ContentTemplate>
    </asp:UpdatePanel>
    
    </div>
    </form>
</body>
</html>
 Monday, May 12, 2008
Monday, May 12, 2008 2:01:26 PM (Eastern Standard Time, UTC-05:00) ( )


User controls are somewhat outdated already with the introduction of partial classes in ASP.NET 2.0 but I still find them useful.  I think of them similar to the include pages in classic ASP. This is a simple example of how to get the text value from a user control on the parent page.

<%@ Page Language="VB" %>
<%@ Register Src="header.ascx" TagName="header" TagPrefix="uc1" %>

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

<script runat="server">

Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
    Dim CompanyName As TextBox = CType(Page.FindControl("Header1$txtCompanyName"), TextBox)
    lblCompanyName.Text = CompanyName.Text   
End Sub
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <!--This is my user control page header-->
     <uc1:header id="Header1" runat="server"></uc1:header>
     <br />
     <br />
     <asp:Label ID="lblCompanyName" runat="server" Text="Label" />     
     <asp:TextBox ID="TextBox1" runat="server" />    
    </div>
    </form>
</body>
</html>

This is an example of how to set the text value from inside the user control on the parent page.

<%@ Control Language="VB" ClassName="header" EnableViewState="false" %>

<script runat="server">
        
    Private Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
        If Not Page.IsPostBack Then                        
            Dim TextBox1 As Textbox =CType(Me.Parent.FindControl("TextBox1"),TextBox)
            TextBox1.Text = "Eat your veggies"            
        End If
    End Sub
</script> <table width="100%" border="0" cellpadding="3" cellspacing="0"> <tr> <td>Company: <asp:Textbox ID="txtCompanyName" runat="server" CssClass="textbox" Text="Company Name" ToolTip="Enter a company name" />
<asp:Button ID="btnCompanySearch" runat="server" Text="go" CssClass="buttons" OnClick="QuickSearch_Companies_Click" /></td> </tr> </table>
 Tuesday, April 29, 2008
Tuesday, April 29, 2008 11:49:27 AM (Eastern Standard Time, UTC-05:00) (  |  )

In the previous example, Using a Timer Control With an Update Panel, we just refreshed a panel from data in a list.  In this more practical example, we pull the data from a live database which refreshes an UpdatePanel and an AJAX script manager.  Here is a working demo.

<%@ 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 id="Head1" runat="server">
    <title>Timer Movies</title>
    <style type="text/css">
    
    .message
    {
        margin-left: 20px;
        font-style:italic;
    }
    
    </style>
</head>
<body>
    <form id="form1" runat="server">
    
    <asp:ScriptManager ID="sm1" runat="server" />
    
    <asp:Timer ID="Timer1" Interval="5000" runat="server" />
    
    <asp:UpdatePanel ID="up1" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
    Last Refresh <%= DateTime.Now.ToString("T") %><hr />
    <asp:ListView
        id="lstMovies"
        DataSourceID="srcMovies"
        Runat="server">
        <LayoutTemplate>
            <div id="itemPlaceholder" runat="server">
            </div>
        </LayoutTemplate>
        <ItemTemplate>
            <div>
                Movie Title: <%# Eval("Title") %><div class="message">
                Director: <%# Eval("Director") %></div>
            </div>    
        </ItemTemplate>
    </asp:ListView>    
    </ContentTemplate>      
    </asp:UpdatePanel>
    
    <asp:ObjectDataSource
        id="srcMovies"
        TypeName="Message"
        SelectMethod="Select"
        Runat="server" />
    
    </form>
</body>
</html>

*** Message.vb ***
Imports System
Imports System.Collections
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Configuration

Public Class Message

    Private _Title As String

    Public Property Title() As String
        Get
            Return _Title
        End Get
        Set(ByVal value As String)
            _Title = value
        End Set
    End Property

    Private _Director As String

    Public Property Director() As String
        Get
            Return _Director
        End Get
        Set(ByVal value As String)
            _Director = value
        End Set
    End Property


    Public Shared Function [Select]() As ArrayList
        Dim results As New ArrayList()
        Dim conString As String = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
        Dim commandText As String = "SELECT Title, Director FROM Movies ORDER BY Id DESC"
        Dim con As New SqlConnection(conString)
        Dim cmd As New SqlCommand(commandText, con)
        Using con
            con.Open()
            Dim reader As SqlDataReader = cmd.ExecuteReader()
            While reader.Read()
                results.Add(New Message(reader))
            End While
        End Using
        Return results
    End Function

    Public Sub New(ByVal reader As SqlDataReader)
        Title = CType(reader("Title"), String)
        Director = CType(reader("Director"), String)
    End Sub

End Class
 
Tuesday, April 29, 2008 9:55:25 AM (Eastern Standard Time, UTC-05:00) (  |  )

This is an interesting example on how to use the Timer control inside of an UpdatePanel to refresh part of a page with no user intervention.   Here is a working demo.

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Collections.Generic" %>
<!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(sender as object, e as EventArgs)
        dim quotes as new List(of string)()
        quotes.Add("A fool and his money are soon parted")
        quotes.Add("A penny saved is a penny earned")
        quotes.Add("An apple a day keeps the doctor away")
        
        dim rnd as new Random()
        lblQuote.Text = quotes(rnd.Next(quotes.Count))
    end sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Timer Quote</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:ScriptManager ID="ScriptManager1" runat="server" />
    
    <asp:Timer ID="Timer1" Interval="2000" runat="server" />

    Page Time: <%= DateTime.Now.ToString("T") %>
    
    <fieldset>
    <legend>Quote</legend>
    <asp:UpdatePanel ID="up1" runat="server">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
    </Triggers>
    <ContentTemplate>
        <asp:Label ID="lblQuote" runat="server" />
    </ContentTemplate>
    </asp:UpdatePanel>
    </fieldset>
        
    </div>
    </form>
</body>
</html>
 Thursday, April 24, 2008
Thursday, April 24, 2008 9:14:46 AM (Eastern Standard Time, UTC-05:00) ( )

The web.config file is commonly used to add database connection strings, mail server settings, system-wide settings etc.  It's easier to store such settings here rather than hard-code them within the pages for obvious reasons. Adding custom key/value pairs in the web.config is pretty easy. Just make sure that the <appSettings> section is outside of the <system.web> section.

<configuration>

<appSettings>
      <add key="myCity" value="Anchorage" />
</appSettings>
<system.web>
....
</system.web>

 

This key/value is accessed in your application like this:

Public Sub Page_Load()
         Dim strCity As String
         strCity = ConfigurationSettings.AppSettings("myCity")
End Sub

Another way to return a custom key's value is to pass the key name to a function.  This function also adds the key name and value to cache if it's not already there

'Return the value of the specified custom key, stored in the Web.Config file.
' If the value has been already requested before, the function returns its 
' cached value.
' The second optional parameter is the path of the Web.Config file where this 
' custom key is stored, and it is necessary to add a dependency to that file,
' so that the cached value is discarded if the file is edited.
' 
' Example: Dim myCity = GetCustomKeyValue("myCity") 

Function GetCustomKeyValue(ByVal key As String, Optional ByVal webConfigUrl As String = "/Web.Config") As String
    ' if this is not the first time this value is needed,
    '  we can find it in the cache
    Dim value As String = CType(HttpContext.Current.Cache(key), String) 

    ' if the retrieved string is empty, the value is not present into the cache,
    '  thus it is retrieved it from Web.Config, and then cached
    If value Is Nothing OrElse value = "" Then
        value = ConfigurationSettings.AppSettings(key)
        HttpContext.Current.Cache.Insert(key, value, New Caching.CacheDependency(webConfigUrl))
    End If 

    Return value
End Function

Lastly, ASP.NET 2.0 makes it really easy to encrypt parts of the web.config to secure sensitive parts of the file. Here are some articles on how to do it.

http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx

http://www.developerfusion.co.uk/show/5263/

http://channel9.msdn.com/Showpost.aspx?postid=134210

Not only can you encrypt config sections using aspnet_regiis from the command line, but you can also encrypt and unencrypt Web.config on the fly in code. The code for protecting and unprotecting sections in your Web.config is fairly trivial, because WebConfigurationManager-related classes handle all the work for you.  I added two buttons to a web page, called btnProtect and btnUnProtect, to protect and unprotect on the fly.  Here is the code of interest:

Protected Sub UnProtect_Click(ByVal sender As Object, ByVal e As EventArgs) 
    UnProtectSection("appSettings") 
End Sub 

Protected Sub Protect_Click(ByVal sender As Object, ByVal e As EventArgs) 
    ProtectSection("appSettings", "DataProtectionConfigurationProvider") 
End Sub 

Private Sub ProtectSection(ByVal sectionName As String, ByVal provider As String) 
    Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) 
    
    Dim section As ConfigurationSection = config.GetSection(sectionName) 
    
    If section IsNot Nothing AndAlso Not section.SectionInformation.IsProtected Then 
        section.SectionInformation.ProtectSection(provider) 
        config.Save() 
    End If 
End Sub 

Private Sub UnProtectSection(ByVal sectionName As String) 
    Dim config As Configuration = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath) 
    
    Dim section As ConfigurationSection = config.GetSection(sectionName) 
    
    If section IsNot Nothing AndAlso section.SectionInformation.IsProtected Then 
        section.SectionInformation.UnprotectSection() 
        config.Save() 
    End If 
End Sub 
 

Here is what the application settings look like when encrypted:

<appSettings configProtectionProvider=
        "DataProtectionConfigurationProvider">
  <EncryptedData>
   <CipherData>
    <CipherValue>
        AQAAANCMnd8BFdERjHoAwE/Cl+sBAAA
        AXmrl4EN1VUSGDS9ZSSydRwQAAAACAA
        AAAAADZgAAqAAAABAAAAA280OtZlZwu
        D3U+ihvi2zpAAAAAASAAACgAAAAEAAA
        AJ6AnDzWM1o3osh/Y6fcYtwAAQAA1PR
        +wzfwgBgZ4y0yHU4uxaaMET13u21Bv3
        zVE7aA7Z5pCWAYs54LNLNYQ673kmzAL
        osWb7OMuzW6BPwMp18gKNQXOFSGNgA1
        ...
    </< SPAN>CipherValue>
   </< SPAN>CipherData>
  </< SPAN>EncryptedData>
</< SPAN>appSettings>
 Wednesday, April 23, 2008
Wednesday, April 23, 2008 12:28:28 PM (Eastern Standard Time, UTC-05:00) (  |  )


Making the selections in a dropdownbox dependent upon the selected item in another one is a pretty simple task. Here is a working demo.

<%@ 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 id="Head1" runat="server">
    <title>Cascading DropDownList Controls With AJAX</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:ScriptManager
        id="sm1"
        Runat="server" />

    <asp:UpdatePanel
        id="UpdatePanel1"
        Runat="server">
   
    <ContentTemplate>
        
    <asp:Label
        id="lblTitle"
        Text="Title:"
        AssociatedControlID="ddlTitle"
        Runat="server" />
    <asp:DropDownList
        id="ddlTitle"
        DataSourceID="srcTitle"
        DataTextField="Title"
        DataValueField="Title"
        AutoPostBack="true"
        Runat="server" />
    <asp:SqlDataSource
        id="srcTitle"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Title FROM Movies ORDER BY Title"
        Runat="server" />
    
    <br /><br />

    
    <asp:Label
        id="Label1"
        Text="Director:"
        AssociatedControlID="ddlDirector"
        Runat="server" />
    <asp:DropDownList
        id="ddlDirector"
        DataSourceID="srcDirector"
        DataTextField="Director"
        AutoPostBack="true"
        Runat="server" />
    <asp:SqlDataSource
        id="srcDirector"
        ConnectionString='<%$ ConnectionStrings:MyDatabase %>'
        SelectCommand="SELECT Director FROM Movies WHERE Title=@Title ORDER BY Title"
        Runat="server">
        <SelectParameters>
            <asp:ControlParameter Name="Title" ControlID="ddlTitle" />
        </SelectParameters>
    </asp:SqlDataSource>    
    
    </ContentTemplate>
    </asp:UpdatePanel>    
    
    </div>
    </form>
</body>
</html>
 Monday, April 21, 2008
Monday, April 21, 2008 2:53:36 PM (Eastern Standard Time, UTC-05:00) (  |  )


There are a lot of ways to grab the number of records returned in a dataset.   This is one of my useful ones. Here is a working demo.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<%@ Import Namespace="System.Web.Configuration" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 
    Private Sub Page_Load()
        lblMovieCount.Text = GetMovieCount().ToString()
    End Sub
 
    Private Function GetMovieCount() As Integer
        Dim result As Integer = 0        

        Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString)

Dim cmd As New SqlCommand("GetMovieCount", con) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.Add("@ReturnVal", SqlDbType.Int).Direction = ParameterDirection.Output Using con con.Open() cmd.ExecuteNonQuery() result = CType(cmd.Parameters("@ReturnVal").Value, Integer) End Using Return result End Function </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head id="Head1" runat="server"> <title>Show Movie Count</title> </head> <body> <form id="form1" runat="server"> <div> There are <asp:Label id="lblMovieCount" Runat="server" /> movies in the database. </div> </form> </body> </html>

GetMovieCount.sql

CREATE PROCEDURE dbo.GetMovieCount 
    -- OUTPUT parameter to hold the count. 
    @ReturnVal int OUTPUT 
AS 
    -- This will set @recordcount the the number of records returned by the SELECT query. 
    Set @ReturnVal = (SELECT COUNT(*) FROM Movies)
 Friday, April 18, 2008
Friday, April 18, 2008 10:22:44 AM (Eastern Standard Time, UTC-05:00) (  |  )


I've been experimenting with LINQ to SQL using code examples from ASP.NET Unleashed 3.5. It's amazing how little code is needed to do some pretty amazing things without ever coding an SQL or ADO.NET. 

In this example, we're using paging on a GridView using a LINQ to SQL class. Paging in a Gridviews typically works by loading all of the records into memory on the server and then displaying only x records at a time.  This, of course, can place a tremendous load on the server if there are a lot of records.  In this example, using LINQ's Skip and Take operators we pass in the the page number and the size creating a much more efficient way to page through a recordset.

The first step is to create an entity using the Object Relational Designer in Visual Studio 2008.    Simply, create a new LINQ to SQL class and then drag whatever table you want from the database on to the designer surface.  In this example, I created a data entity named Movie along with a class named MoviesLINQPaging.  Inside of my class I created two methods named GetMovies and GetMovieCount. 

Here is a working demo

App_Code/MoviesLINQPaging.vb

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Data.Linq
Imports System.Web

Public Class MoviesLINQPaging

    Public Shared Function GetMovies(ByVal startRowIndex As Integer, ByVal maximumRows As Integer) As IEnumerable(Of Movie)
        Dim db As New MoviesDataContext()
        Return db.Movies.Skip(startRowIndex).Take(maximumRows)
    End Function

    Public Shared Function GetMovieCount() As Integer
        Dim context As HttpContext = HttpContext.Current
        If IsNothing(context.Cache("MovieCount")) Then
            context.Cache("MovieCount") = GetMovieCountFromDB()
        End If
        Return CType(context.Cache("MovieCount"), Integer)
    End Function

    Private Shared Function GetMovieCountFromDB() As Integer
        Dim db As New MoviesDataContext()
        Return db.Movies.Count()
    End Function

End Class

The next step is to create new aspx page with a gridview which uses a ObjectDataSource to display the data. Notice the properties of the ObjectDataSource:  TypeName="MoviesLINQPaging" - this is the class name found in MoviesLINQPaging.vb. SelectMethod="GetMovies" and SelectCountMethod="GetMovieCount" are the two methods inside the MoviesLINQPaging class.

MoviesLINQPaging.aspx
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        .movies td,.movies th
        {
            padding:5px;
        }
    </style>
    <title>Show LINQ Paging</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        AllowPaging="true"
        PageSize="3"
        CssClass="movies"
        Runat="server" />
        
    <asp:ObjectDataSource
        id="srcMovies"
        TypeName="MoviesLINQPaging"
        SelectMethod="GetMovies"
        SelectCountMethod="GetMovieCount"
        EnablePaging="True"
        Runat="server" />    
    
    </div>
    </form>
</body>
</html>
 Tuesday, April 15, 2008
Tuesday, April 15, 2008 2:03:57 PM (Eastern Standard Time, UTC-05:00) (  |  )

You can use all of the same types of parameters with the ObjectDataSource control that you can use with the SqlDataSource

control.  See this page for more info and a demo.

Tuesday, April 15, 2008 2:00:01 PM (Eastern Standard Time, UTC-05:00) (  |  )

In this example notice that the ObjectDataSource control includes an UpdateMethod property that points to the UpdateMovie() method. See a working demo of this.

The GridView automatically adds the update parameters to the ObjectDataSource control's UpdateParameter collection. As an alternative, you can declare the parameters used by the ObjectDataSource control explicitly.  See this example for details on this.

 

*** Movies.vb ***

Imports System.Web.Configuration

Public Class Movies

    Private ReadOnly _conString As String

    Public Sub UpdateMovie(ByVal id As Integer, ByVal title As String, &_ 
    ByVal director As String, ByVal dateReleased As DateTime)
        ' Create Command
        Dim con As New SqlConnection(_conString)
        Dim cmd As New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "UPDATE Movies SET Title=@Title,Director=@Director,&_ 
        DateReleased=@DateReleased WHERE Id=@Id"

        ' Add parameters
        cmd.Parameters.AddWithValue("@Title", title)
        cmd.Parameters.AddWithValue("@Director", director)
        cmd.Parameters.AddWithValue("@DateReleased", dateReleased)
        cmd.Parameters.AddWithValue("@Id", id)

        ' Execute command
        Using con
            con.Open()
            cmd.ExecuteNonQuery()
        End Using
    End Sub

    Public Function GetMovies() As SqlDataReader
        ' Create Connection
        Dim con As New SqlConnection(_conString)

        ' Create Command
        Dim cmd As SqlCommand = New SqlCommand()
        cmd.Connection = con
        cmd.CommandText = "SELECT Id,Title,Director,DateReleased FROM Movies"

        ' Return DataReader
        con.Open()
        Return cmd.ExecuteReader(CommandBehavior.CloseConnection)
    End Function

    Public Sub New()
        _conString = WebConfigurationManager.ConnectionStrings("MyDatabase").ConnectionString
    End Sub

End Class


*** ShowMovies.aspx ***

<%@ Page Language="VB" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show Movies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdMovies"
        DataSourceID="srcMovies"
        DataKeyNames="Id"
        AutoGenerateEditButton="true"
        Runat="server" />
        
    <asp:ObjectDataSource
        id="srcMovies"
        TypeName="Movies"
        SelectMethod="GetMovies"
        UpdateMethod="UpdateMovie"
        Runat="server"/>
    
    </div>
    </form>
</body>
</html>
 Monday, April 14, 2008
Monday, April 14, 2008 2:00:29 PM (Eastern Standard Time, UTC-05:00) ( )

 

As long as all of the components in the App_Code folder are in the same language then you don't have to do anything special. However, if you want place components written in different languages - for example C# and VB.NET, then you need to place components in different languages in different subfolders.  You also need to modify the web.config file to recognize the different subfolders.

Web.Config

<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName="VBCode" />
<add directoryName="CSCode" />
</ codeSubDirectories>
</ configuration>
</ system.web>
</ compilation>

 Thursday, April 10, 2008
Thursday, April 10, 2008 10:32:18 AM (Eastern Standard Time, UTC-05:00) (  |  )

There are several ways to add client-side javascript to a ASP.NET page depending on your needs.  Other than using the traditional method of just adding a <script> section in the <head> section of the page, but what if want to reference that javascript across multiple pages?  Here are a few other methods.

Using an external .js file

You could just reference an external .js file like this:

<script language="javascript" src="scroller.js"></script>

 

Using a master page

This approach uses the ClientScriptManager to register a client-side script in a master page and makes it accessible across the whole site.

--masterpage.master

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>
<!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>Untitled Page</title>
</head>
<body onload="displayTime()">
  <form id="form1" runat="server">
    <div>
      <div>
        HEADER
        <div id="currentTime">
        </div>
      </div>
      <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      </asp:ContentPlaceHolder>
    </div>
  </form>
</body>
</html>

--MasterPage.master.vb

Partial Class MasterPage
    Inherits System.Web.UI.MasterPage

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim scriptName As String = "DisplayTime"
    Dim scriptUrl As String = "~/Scripts/DisplayTime.js"
    Dim scriptType As Type = Me.GetType()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript

    If (Not clientScriptManager.IsClientScriptIncludeRegistered(scriptType, scriptName)) Then
      clientScriptManager.RegisterClientScriptInclude(scriptType, scriptName, ResolveClientUrl(scriptUrl))
    End If

  End Sub
End Class
 

Build the javascript as a string and register it

Rather than reference an external javascript file, you can use the RegisterClientScriptBlock method along with the StringBuilder method to register some javascript in your page.
 
<%@ Page Language="VB" AutoEventWireup="false"
  CodeFile="Default3.aspx.vb" Inherits="Default3" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  <div>
    <input type="button" value="Change Color" onclick="changeColor('blue')" />
  </div>
</asp:Content>
 
Partial Class Default3
    Inherits System.Web.UI.Page

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript
    Dim sb As StringBuilder = New StringBuilder()

    sb.Append("<script language='javascript'>")
    sb.Append("function changeColor(color) {")
    sb.Append("document.bgColor=color;")
    sb.Append("}")
    sb.Append("<")
    sb.Append("/script>")

    If (Not clientScriptManager.IsClientScriptBlockRegistered("ColorScript")) Then
      clientScriptManager.RegisterClientScriptBlock(Me.GetType(), "ColorScript", sb.ToString())
    End If

  End Sub
End Class
 

Build the javascript as a string and register it on startup

Lastly, using the same approach as above except for this time the javascript doesn't get registered until the page starts using the RegisterStartupScript method

 
Partial Class Default4
    Inherits System.Web.UI.Page

  Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
    LoadScript()
  End Sub

  Private Sub LoadScript()

    Dim clientScriptManager As ClientScriptManager = Page.ClientScript
    Dim sb As StringBuilder = New StringBuilder()

    sb.Append("<script language='javascript'>")
    sb.Append("document.bgColor='green';")
    sb.Append("<")
    sb.Append("/script>")

    If (Not clientScriptManager.IsStartupScriptRegistered("ColorScript")) Then
      clientScriptManager.RegisterStartupScript(Me.GetType(), "ColorScript", sb.ToString())
    End If


  End Sub

End Class