Navigation

Search

Categories

On this page

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
How to Share Data Between Stored Procedures
Using the Gridview.Sorting and Gridview.Sorted Events
Sharing Client-Side Code with Server-Side Code
Using Javascript with ASP.NET
First Look at Silverlight 2.0

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: 112
This Year: 50
This Month: 4
This Week: 0
Comments: 0

Sign In

 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
 Wednesday, April 09, 2008
Wednesday, April 09, 2008 11:12:57 AM (Eastern Standard Time, UTC-05:00) ( )


Allowing users to select a theme for a site is a cool option and is pretty easy to do.  In these examples, I'll show how to allow a user to select a theme from a dropdownlist for a single page and for a master page which will carry the theme throughout the whole site.

The first step is to actually create your themes.  This is done by creating a App_Themes folder in the root of the site and then creating a separate folder for each theme beneath this one. For example, App_Themes/ThemeGreen/style.css,  App_Themes/ThemeBrown/style.css etc.

A Single Page

The theme for a page is created early during the page lifecycle - the page_preinit stage so we have to establish the theme at this point.

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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">
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem Value="ThemeGreen">Theme Green</asp:ListItem>
        <asp:ListItem Value="ThemeBrown">Theme Brown</asp:ListItem>
      </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Default.aspx.vb

Partial Class _Default
    Inherits System.Web.UI.Page

  Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
    If (Not Request.Form Is Nothing And Request.Form.Count > 0) Then
      Me.Theme = Request.Form("DropDownList1")
    End If
  End Sub
End Class
A Master Page

--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" />
<body>
  <form id="form1" runat="server">
    <div>
      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem Value="ThemeBlue">Theme Blue</asp:ListItem>
        <asp:ListItem Value="ThemeRed">Theme Red</asp:ListItem>
      </asp:DropDownList>
    </div>   
  </form>
</body>
</html>
--masterpage.master.vb
Partial Class MasterPage
  Inherits System.Web.UI.MasterPage
End Class
--default3.aspx
<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"
  CodeFile="Default3.aspx.vb" Inherits="Default3" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
  Selectable them in master page drop down list set in a new base class (BasePage)
  which replaces Page as the parent for the page.
</asp:Content>
--default3.aspx.vb
Partial Class Default3
  Inherits BasePage
End Class

--App_Code/BasePage.vb

Imports Microsoft.VisualBasic

''' <summary>
''' Base class for Theme based pages.
''' </summary>
Public Class BasePage
  Inherits Page

  Protected Overrides Sub OnPreInit(ByVal e As System.EventArgs)
    MyBase.OnPreInit(e)
    If (Not Request.Form Is Nothing And Request.Form.Count > 0) Then
         Me.Theme = Request.Form(Me.Master.FindControl("DropDownList1").UniqueID)
    End If
  End Sub
End Class

 Tuesday, April 08, 2008
Tuesday, April 08, 2008 12:35:23 PM (Eastern Standard Time, UTC-05:00) ( )


Erland Sommarskog, a SQL Server MVP, has a nice entry on how to share data between stored procedures.  The example I'll use the most often is using OUTPUT parameters

This method can only be used when the result set is one single row. Nevertheless, this is a method that is sometimes overlooked. Say you have this simple stored procedure:

CREATE PROCEDURE insert_customer @name    nvarchar(50),
                                 @address nvarchar(50),
                                 @city    nvarchar(50) AS
DECLARE @cust_id int
BEGIN TRANSACTION
SELECT @cust_id = coalesce(MAX(cust_id), 0) + 1 FROM customers (UPDLOCK)
INSERT customers (cust_id, name, address, city)
   VALUES (@cust_id, @name, @address, @city)
COMMIT TRANSACTION
SELECT @cust_id
That is, the procedure inserts a row into a table, and returns the id for the row.

Rewrite this procedure as:

CREATE PROCEDURE insert_customer @name    nvarchar(50),
                                 @address nvarchar(50),
                                 @city    nvarchar(50),
                                 @cust_id int OUTPUT AS
BEGIN TRANSACTION
SELECT @cust_id = coalesce(MAX(cust_id), 0) + 1 FROM customers (UPDLOCK)
INSERT customers (cust_id, name, address, city)
   VALUES (@cust_id, @name, @address, @city)
COMMIT TRANSACTION

You can now easily call insert_customer from another stored procedure. Just recall that in T-SQL you need to specify the OUTPUT keyword also in the call:

EXEC insert_customer @name, @address, @city, @cust_id OUTPUT
Tuesday, April 08, 2008 11:53:34 AM (Eastern Standard Time, UTC-05:00) (  |  )


If you're using a SQLDataSource, it's pretty simple to add sorting to a Gridview.  But often times we need some specific event to occur when we sort a column such as change the text in a label control, add ASC or DESC up and down arrows to indicate how a Gridview is being sorted, databind some other object on the page etc.  Below are two examples - the first one uses the Gridview.Sorting event and the last one uses Gridview.Sorted.

<script runat="server">

  Sub CustomersGridView_Sorting(sender As Object, e As GridViewSortEventArgs)

    ' Cancel the sorting operation if the user attempts
    ' to sort by address.
    If e.SortExpression = "Address" Then

      e.Cancel = True
      Message.Text = "You cannot sort by address."
      SortInformationLabel.Text = ""

    Else

      Message.Text = ""

    End If

  End Sub

  Sub CustomersGridView_Sorted(ByVal sender As Object, ByVal e As EventArgs)

    ' Display the sort expression and sort direction.
    SortInformationLabel.Text = "Sorting by " & _
      CustomersGridView.SortExpression.ToString() & _
      " in " & CustomersGridView.SortDirection.ToString() & _
      " order."

  End Sub

</script>

<html  >
  <head runat="server">
    <title>GridView Sorted and Sorting Example</title>
</head>
<body>
    <form id="form1" runat="server">

      <h3>GridView Sorted and Sorting Example</h3>

      <asp:label id="Message"
        forecolor="Red"
        runat="server"/>

      <br/>

      <asp:label id="SortInformationLabel"
        forecolor="Navy"
        runat="server"/>

      <br/>  

      <asp:gridview id="CustomersGridView" 
        datasourceid="CustomersSource" 
        autogeneratecolumns="true"
        allowpaging="true"
        emptydatatext="No data available." 
        allowsorting="true"
        onsorting="CustomersGridView_Sorting"
        onsorted="CustomersGridView_Sorted"  
        runat="server">

      </asp:gridview>
<asp:sqldatasource .... />
 Friday, April 04, 2008
Friday, April 04, 2008 1:41:59 PM (Eastern Standard Time, UTC-05:00) (  |  )


I often come across the need to share data between javascript client-side code and my asp.net server controls.  Many functions just perform better on the client-side and the need to pass data from my server controls to javascript comes up often.  One of the easier ways of doing this is to create a asp:hiddenfield. Doing this gives your javascript code access to the data it contains.  In this example, we programatically create a asp:Hiddenfield with a ID="sharedData" and assign a value of "New client initial value." When we click the server-side button, btnGetData which calls the javascript function getSharedData(), it passes the hiddenfield value from sharedData to getSharedData().

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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>Untitled Page</title>
    <script type="text/javascript">
    function getSharedData()
    {
        alert("Shared data is " + document.getElementById("sharedData").value + ".");
    }
    
    </script>    
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
        <asp:Button ID="btnGetData" runat="server" Text="Get Data" OnClientClick="getSharedData()" />
    </form>
</body>
</html>
Code behind - Default.aspx.vb:
Partial Class Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreLoad
        Dim hiddenField As System.Web.UI.WebControls.HiddenField = New System.Web.UI.WebControls.HiddenField
        hiddenField.ID = "sharedData"
        hiddenField.Value = "New client initial value"

        Page.Form.Controls.Add(hiddenField)
    End Sub
End Class
 Thursday, March 20, 2008
Thursday, March 20, 2008 2:53:14 PM (Eastern Standard Time, UTC-05:00) (  |  )

I've been working on a project which required the use of some javascript with some server-side controls. I spent considerable time monkeying around with the Page.ClientScript.RegisterClientScriptBlock() method which registers a client script on the page. I couldn't quite get it right using this method and ended up with a much simpler approach anyway.  Every server-side web control has an "Add" method which you can use when the page loads.   In the example below, I register a click event for a button and 2 different textboxes.  Take notice that for the textboxes I use the client side id value for them (e.g. 'Header1_txtFirstName').  These values can be obtained by looking at the source code of the page in the browser.

Private Sub Page_Load(ByVal Src As Object, ByVal E As EventArgs)
        If Not Page.IsPostBack Then
            btnDelete.Attributes.Add("onClick", "return confirm('You sure you want to delete the record?');")
            txtFirstName.Attributes.Add("onClick", "document.getElementById('Header1_txtFirstName').value = '';")
            txtLastName.Attributes.Add("onClick", "document.getElementById('Header1_txtLastName').value = '';")
        End If
End Sub
Candidate Name: 
<asp:TextBox ID="txtFirstName" runat="server" Text="First Name" /> 'this becomes Header1_txtFirstName
<asp:TextBox ID="txtLastName" runat="server" Text="Last Name" /> 'this becomes Header1_txtLastName
More information on this topic here: http://dotnetslackers.com/articles/aspnet/JavaScript_with_ASP_NET_2_0_Pages_Part1.aspx
 Tuesday, March 11, 2008
Tuesday, March 11, 2008 10:45:50 AM (Eastern Standard Time, UTC-05:00) ( )

 

Scott Gutherie has a nice 8 part tutorial series on Silverlight 2.0 as well as a nice blog post on Expression Blend with Silverlight 2.