History   |   Planning   |   HTML/CSS   |   JavaScript   |   ASP   |   .Net 1.0   |   .Net 2.0   |   .Net 3.0   |   C#   |   Java   |   SQL   |   XML   |   GIS   |   Software   |   Glossary
.Net 2.0
    - AJAX

    - Align

    - Array

    - Base Page

    - Bookmark

    - Buttons

    - Checkbox

    - Conn String

    - ControlParameter

    - Convert

    - Database

    - Date

    - Delete Confirm

    - DropDown

    - Errors

    - Events

    - External Process

    - Fields

    - Files

    - Format

    - Formview

    - GridView

    - HashTable

    - HasValue

    - HyperLink

    - JavaScript

    - NULL

    - Nothing

    - Object Test Bench

    - Page

    - Page Methods

    - Pagination

    - Panel

    - Postback

    - PreRender

    - RegularExpression

    - Rounding

    - String

    - Source Control

    - TableAdapter

    - TimeTracker

    - Using

    - ValidateRequest

    - Visual Dev. Exp.

    - Web.config

    - Web Admin Tool

    - Web Parts

    - Web Service

    - XSD File

 
.Net 2.0 : AJAX
ASP.NET AJAX Control Toolkit
URL: http://www.asp.net/ajax/ajaxcontroltoolkit/samples/
AJAX Auto Update
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ACT" %>

<asp:ScriptManager ID="ScriptManager1" runat="server" />

<asp:UpdatePanel ID="updVersion" runat="server" UpdateMode="Conditional"> 
	<ContentTemplate>
		<asp:DropDownList ID="drpVersion" runat="server" AutoPostBack="True" 
			DataSourceID="sdsVersionsTier1" DataTextField="VERSION" DataValueField="VERSION" />
	</ContentTemplate>
	<Triggers>
		<asp:AsyncPostBackTrigger ControlID="drpProgramName" EventName="SelectedIndexChanged" />
	</Triggers> 
</asp:UpdatePanel>
AJAX Calendar
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ACT" %>

<asp:TextBox ID="txtPeakDate" MaxLength="10" runat="server" />
<ACT:CalendarExtender ID="calPeakDate" TargetControlID="txtPeakDate" runat="server" />
Jump to Top
.Net 2.0 : Align
Table Align
<table style="width:90%; margin:0 auto" cellpadding="0" cellspacing="0" border="0">
DIV Align
<div style="text-align: center;">
Jump to Top
.Net 2.0 : Array
Public Function GetFirstNames() As Array
	Dim firstName() As String = {"Adam", "Bravo", "Charlie", "Echo"}

	Return firstName
End Function
Jump to Top
.Net 2.0 : Base Page
SiteMap Title - Class
Public Class MyBasePage
Inherits System.Web.UI.Page
	Sub New()
	
	End Sub

	Protected Overrides Sub Onload(ByVal e As System.EventArgs)
		MyBase.OnLoad(e)
		SetTittle()
	End Sub

	Protected Sub SetTitle()
		If SiteMap.CurrentNode IsNot Nothing Then
			Me.Title = SiteMap.CurrentNode.Title.ToString()
		End If
	End Sub
End Class
SiteMap Title - Page
Partial Class Contact
Inherits MyBasePage
Jump to Top
.Net 2.0 : Bookmark
Ctrl+K, Ctrl+K - Create/Remove Bookmark
Ctrl+K, Ctrl+N  - Move to next bookmark
Ctrl+K, Ctrl+P -  Move to previous bookmark
Ctrl+K, Ctrl+L - Clear all bookmarks
Jump to Top
.Net 2.0 : Buttons
LinkButton
The CommandArgument property complements the CommandName property by allowing you to 
provide additional information about the command to perform. For example, if you set the 
CommandName property to Approve and the CommandArgument property to Manager, you can
pass the value "Manager" to the method.

' Page
<asp:LinkButton id="btnManager" Text="Manager Approval" CommandName="Approve" CommandArgument="Manager" 
OnCommand="CommandBtn_Click" runat="server"/>

' Code Behind
Sub CommandBtn_Click(sender As Object, e As CommandEventArgs) 
	Select e.CommandName
		Case "Approve"
			' Call the method to approve the record.
			Sort_List(CType(e.CommandArgument, String))
		Case "Void"
			' Call the method to void the record.
	End Select
End Sub
Button
' Page
<asp:Button ID="btnMarkOk" Text="Mark Ok" Runat="server" />

' Code Behind
Protected Sub btnMarkOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMarkOk.Click
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after a button outside of the GridView is clicked.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' DataKey
	Dim f_sCustomerId As String = String.Empty
	f_sCustomerId = grdContacts.DataKeys(i).Values("CUSTOMER_ID").ToString()
End Sub
ImageButton
' Page
<asp:ImageButton  ID="btnAdminApprove" Text="Approve" Runat="server" />

' Code Behind
Sub btnAdminApprove_Click(ByVal sender As Object, ByVal e As ImageClickEventArgs)
	Label1.Text = "You clicked the ImageButton control at the coordinates: (" & _
		e.X.ToString() & ", " & e.Y.ToString() & ")"
End Sub
Do Not Validate
<asp:Button ID="btnCancel" Text="Cancel" CausesValidation="False" runat="server" />
Jump to Top
.Net 2.0 : Checkbox
Page
<asp:GridView ID="grdCharges" runat="server" AllowPaging="True" AutoGenerateColumns="False"  
DataKeyNames="BILL_CUST_ID,START_PERIOD,END_PERIOD" DataSourceID="odsCharges"
Width="800px" CellPadding="3" BorderWidth="0px" EmptyDataText="No records to display.">                  
	<Columns>
		<asp:TemplateField HeaderText="Mark Ok">
			<ItemTemplate>
				<asp:CheckBox ID="chkMarkOk" runat="server" />
			</ItemTemplate>
		</asp:TemplateField>
		<asp:BoundField DataField="BILL_CUST_ID" HeaderText="Agency" />
		<asp:BoundField DataField="START_PERIOD" HeaderText="Start Period" />
		<asp:BoundField DataField="END_PERIOD" HeaderText="End Period" />
	</Columns>
	<HeaderStyle BackColor="#D5DFF3" Font-Bold="True" Font-Names="Verdana" />
	<AlternatingRowStyle BackColor="#EEEEEE" />
</asp:GridView>
Code Behind
Protected Sub btnMarkOk_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMarkOk.Click
	Dim f_sKey1 As String = String.Empty
	Dim f_sKey2 As String = String.Empty
	Dim f_sKey3 As String = String.Empty
	Dim cbMarkOk As System.Web.UI.WebControls.CheckBox
	Dim i As Integer
	Dim f_oTableAdapter As New InvoiceInfoTableAdapters.12B_CHG_CRCTableAdapter
	Dim f_sReturn As String

	For i = 0 To grdCharges.Rows.Count - 1

		cbMarkOk = grdCharges.Rows(i).FindControl("chkMarkOk")

		If (cbMarkOk.Checked) Then
			f_sKey1 = grdCharges.DataKeys(i).Values("BILL_CUST_ID").ToString()
			f_sKey2 = grdCharges.DataKeys(i).Values("START_PERIOD").ToString()
			f_sKey3 = grdCharges.DataKeys(i).Values("END_PERIOD").ToString()
		
			'Mark Ok Method
			f_sReturn = f_oTableAdapter.UpdateOK(drpAgencies.SelectedValue, f_sKey2, f_sKey3,
			Date.Today, My.User.Name, My.User.Name)
		End If
	Next

	If f_sReturn.ToLower = "record updated" Then
		lblMessage.Text = "Records marked Ok have been updated."
	Else
		lblMessage.Text = "An error occured. Please contact support and report the following: " & f_sReturn
	End If

	Me.grdCharges.DataBind()

	f_oTableAdapter.Dispose()
End Sub
Jump to Top
.Net 2.0 : Conn String
Web.config
<configuration>
	<connectionStrings>
		<add
		name="MyConnectionString"
		providerName="System.Data.SQLClient"
		connectionString="Data Source=SQL01; Initial Catalog=Store; User ID=sa; Password=111111" />
	</connectionStrings>
</configuration>
Code
ConfigurationManager.ConnectionStrings("MyConnectionString").ConnectionString
Other
' Web.Config
<configuration>
	<appSettings/>
		<connectionStrings>
			<add name="CHGSQL" connectionString="
			Server=CHGSQL;
			Database=TimeTracker;
			User ID=sa;
			Password=profit$;
			Trusted_Connection=False"
			providerName="System.Data.SqlClient" />
		</connectionStrings>

' Code
using System.Configuration;

SqlConnection conn = new
SqlConnection(ConfigurationManager.ConnectionStrings["CHGSQL"].ConnectionString);
Jump to Top
.Net 2.0 : Control Param
ControlParameter vs. FormParameter in a MasterPage
More Info: Mands Consulting
<asp:ObjectDataSource ID="odsPrograms" runat="server" OldValuesParameterFormatString="original_{0}"
    SelectMethod="GetProgram" TypeName="WINS.DataTier.CertificationInfoTableAdapters.CERT_LPPTableAdapter">
    <SelectParameters>
        <asp:ControlParameter ControlID="ddlMeters" Name="cmbMeter" PropertyName="SelectedValue" Type="String" DefaultValue="N/A" />
        <asp:ControlParameter ControlID="OccurPrdTextBox" Name="dfOCCUR_PERIOD" PropertyName="Text" Type="String" DefaultValue="N/A" />
    </SelectParameters>
</asp:ObjectDataSource>
Jump to Top
.Net 2.0 : Convert
String to Decimal
f_dAmt = Convert.ToDecimal(f_sAmt)
String to Date
f_sRegDate = DateTime.Parse(f_sRegDate)
Jump to Top
.Net 2.0 : Database
Call a Stored Procedure
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Public Function Delete(ByVal vDataSourceID As Integer) As Boolean
	Dim f_oConnection As New SqlConnection(ConfigurationSettings.AppSettings("ConnectionString"))
	Dim f_oCommand As New SqlCommand("dc_source_delete", f_oConnection)

	f_oCommand.CommandType = CommandType.StoredProcedure

	Dim f_iDataSourceID As New SqlParameter("@data_source_id", SqlDbType.Int, 4)
	f_iDataSourceID.Value = vDataSourceID
	f_oCommand.Parameters.Add(f_iDataSourceID)

	f_oConnection.Open()
	f_oCommand.ExecuteNonQuery()
	f_oConnection.Close()

	Return True
End Function
Return a Single Value : Oracle : No Proc
Public Function WONumberGet(ByVal vSRNo As Integer) As Integer
        Dim dbConnection As OracleConnection
        Dim connectionString As String = Nothing
        Dim command As OracleCommand = Nothing
        Dim workOrderNumber As Integer = 0
        Try
            connectionString = Config.ORACLE_CONNECTION_STRING
            dbConnection = New OracleConnection(connectionString)

            Dim sql = "SELECT WO_NUMBER FROM wo_xref WHERE SR_NO = " & vSRNo
            Dim cmd As New OracleCommand(sql, dbConnection)
            dbConnection.Open()
            workOrderNumber = cmd.ExecuteOracleScalar
        Catch ex As Exception
            LogManager.AddToFile("ERROR: WONumberGet: " & Date.Now & ", " & ex.Message)
        End Try
retVal:
        Return workOrderNumber
End Function
Jump to Top
.Net 2.0 : Date
Last Day of Month, Check if Weekend
Private Function InvDueDate(ByVal vNextActiveBillPeriod As String) As Date
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' Compute the due date as two months from the last day of the billed month. 
	' Make sure the date is not a Sunday or Saturday.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_sNextActiveBPMonth As String
	Dim f_sNextActiveBPYear As String
	Dim f_sDueDate As String
	Dim f_dDueDateTemp As Date
	Dim f_dDueDate As Date
	Dim f_dLastDayOfMonth As Date

	f_sNextActiveBPMonth = vNextActiveBillPeriod.Substring(4, 2)
	f_sNextActiveBPYear = vNextActiveBillPeriod.Substring(0, 4)
	f_sDueDate = f_sNextActiveBPMonth & "/" & "1" & "/" & f_sNextActiveBPYear
	f_dDueDateTemp = DateAdd(DateInterval.Month, 2, CDate(f_sDueDate))
	f_dLastDayOfMonth = New Date(f_dDueDate.Year, f_dDueDate.Month, 1).AddMonths(1).AddDays(-1)
	f_dDueDate = New Date(f_dDueDateTemp.Year, f_dDueDateTemp.Month, f_dLastDayOfMonth.Day)

	Select Case f_dDueDate.DayOfWeek
		Case DayOfWeek.Saturday
			f_dDueDate = DateAdd(DateInterval.Day, -1, f_dDueDate)
		Case DayOfWeek.Sunday
			f_dDueDate = DateAdd(DateInterval.Day, -2, f_dDueDate)
	End Select

	Return f_dDueDate
End Function
Jump to Top
.Net 2.0 : Delete Confirm
<asp:TemplateField>
	<ItemTemplate>
		<asp:LinkButton ID="btnDelete" runat="server" OnClientClick="return confirm('Are you sure 
			you want to delete this product?');" CommandName="Delete">delete</asp:LinkButton>
	</ItemTemplate>
</asp:TemplateField> 
Jump to Top
.Net 2.0 : Dropdown
Check if Empty
If DropDownList1.Items.Count = 0 Then
	'...
End If
Add Item
' ASP.Net 1.1
 
ddlAgency.Items.Insert(0, New ListItem("MWD", "MWD"))


' ASP.Net 2.0

<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="true">  
	<asp:ListItem Value="">Please select a country</asp:ListItem>
</asp:DropDownList>
Jump to Top
.Net 2.0 : Errors
.Net
ERROR:
"Visual Studio .NET has detected that the specified Web server is not running ASP.NET version 1.1. You will need to run ASP.NET Web Applications or services."

SOLUTION:
(1) C:\> cd windows\microsoft.net\framework\v1.1.4322
(2) C:\windows\microsoft.net\framework\v1.1.4322> aspnet_regiis -i
 
ERROR:
"Unable to start debugging on the web server. The web server is not configured correctly. See help for common configuration errors. Running the web page outside of the debugger may provide further information."

SOLUTION 1:
(1) C:\> cd windows\microsoft.net\framework\v2.0.50727
(2) C:\windows\microsoft.net\framework\v2.0.50727> aspnet_regiis -i

SOLUTION 2:
(1) C:\> cd windows\microsoft.net\framework\v1.1.4322
(2) C:\windows\microsoft.net\framework\v1.1.4322> aspnet_regiis -i

SOLUTION 3:
Make sure that the proper .Net version is selected in IIS for that website.
 
ERROR:
"Login failed for user 'sa'. Reason: Not associated with a trusted SQL Server connection."

SOLUTION:
If Windows Authentication mode is selected during installation, the sa login is disabled.
 
ERROR:
"Server Application Unavailable"

SOLUTION:
Make sure that .Net 1 apps are in one Application Pool and .Net 2 are in another.
 
ERROR:
When attempting to run your app which has a GridView/ObjectDataSource, you get a strange message that says it cannot find a method with that name and params such as "generic_".

SOLUTION:
Go to your ObjectDataSource...

OldValuesParameterFormatString="original_{0}"

and change it to...

OldValuesParameterFormatString="original_{0}"
 
ERROR:
"Can't find method"

SOLUTION:
When attempting to attach a method to an ObjectDataSource, it does not appear in the drop down (ex: ChargesUpdate). You may see a generic one called "Update". Go to the .xsd file and select the DataTable and view the properties. In the properties window, remove the auto created methods (DeleteCommand, InsertCommand...).
 
ERROR:
invalid postback or callback argument. Event validation is enabled using...

SOLUTION:
Change:

<pages validateRequest="false" />

To:

<pages validateRequest="false" enableEventValidation="false" />
 
ERROR:
"The 'DataSource' property cannot be set declaratively"

SOLUTION:
Make sure you have DataSourceID="SqlDataSource1" not DataSource="SqlDataSource1" in your GridView.
 
ERROR:
"Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints."

SOLUTION:
Due to a mismatch between the TableAdapter and the specific query with regards to the amount of columns. If the TableAdapter is defined as...

Select * FROM table_a
and the specific Fill Method/Get Method / Query is
SELECT field1 FROM table_a

or

SELECT DISTINCT field1 FROM table_a

and table_a has more than one column,for instance, the exception will be thrown. I saw this by 'previewing' the data with the designer. (Right click on the Query in the designer, and choose preview). The fields not listed in the query were empty, and that's what the exception is barking about. The TableAdapter Query must have the same columns as the individual Queries attached to it.

It makes sense, if you think about it. The Fill/Get method of the TableAdapter is really creating a specific type of DataSet, and if you're missing fields, the binding doesn't work properly.

CGJ - select configure for the Fill, GetData() TableAdapter and copy the fields. Paste the into FillMeterByOrgID, GetMeterByOrgID(OrgID) configuration (previously only had the a select on the MeterID).
 
ERROR:
Delete and Edit not enabled on your .Net 2.0 GridView.

SOLUTION:
Make sure your datasource has a primary key.
 
ERROR:
String[1]: the Size property has an invalid size of 0.

SOLUTION:
Make sure you specify a size for all your char stored proc params (even output)...

objComm.Parameters.Add(New OleDbParameter("Password", NPPassword))
objComm.Parameters(1).OleDbType = OleDbType.VarChar
objComm.Parameters(1).Direction = ParameterDirection.Output
objComm.Parameters(1).Size = 100
 
ERROR:
Reference to a non-shared member requires an object reference.

SOLUTION:
Make sure you have a reference to the object that you are using...

Using ObjConn As New OracleConnection(Config.ORACLE_CONNECTION_STRING)

REFERENCE: System.Data.OracleClient
 
Oracle
ERROR:
OCI-22053: overflow error

SOLUTION:
Truncate the decimal field to 2 decimal places. You probably have on field returning a value such as 3.27927120669056....

TRUNC(cc_charge, 2)
 
ERROR:
ORA-12545: Connect failed because target host or object does not exist

SOLUTION:
I had the connection string value commented out.
 
ERROR:
ORA-12514: TNS:listener does not currently know of service requested in connect descriptor

SOLUTION:
Needed to install the Windows Service which talks to Oracle server on the D: drive where the TNSNAMES.ORA is located (not C:).
 
ERROR:
ORA-00936: missing expression

SOLUTION:
Needed to add single quotes around my variables that are strings when passing them in a SQL statement.
 
IIS
ERROR:
"It is not possible to run two different versions of ASP.NET in the same IIS process. Please use the IIS Administration Tool to reconfigure your server to run the application in a separate process."

SOLUTION:
Keep .Net 1 apps in one App Pool and .Net 2 in another -- http://weblogs.asp.net.
 
SQL
ERROR:
"String or binary data would be truncated"

SOLUTION:
-- Add the following to your stored proc...
SET ANSI_WARNINGS OFF

-- When set to ON, if null values appear in aggregate functions, such as SUM, AVG, MAX, MIN, STDEV,
-- STDEVP, VAR, VARP, or COUNT, a warning message is generated. When set to OFF, no warning is issued.
 
WINDOWS
ERROR:
Active Desktop Recovery: "Object doesn’t support this action"

SOLUTION:
> regedit

Go to this key: HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Desktop\SafeMode\Components

Change the value of DeskHtmlVersion to zero instead of decimal 272.
Jump to Top
.Net 2.0 : External Process
PDF File
Imports System.Diagnostics

Protected Sub btnPreview_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnPreview.Click
	' (1) Check if file exists
	Dim f_sFileDirectory As String = ConfigurationManager.AppSettings("InvoicePrintPDFDir")
	Dim f_sFilePath As String = f_sFileDirectory & "\" & drpBillPeriods.SelectedValue & "\" & "invoice-" & _
		drpBillPeriods.SelectedValue & "-" & drpAgencies.SelectedValue & ".pdf"
	Dim f_sAcrobatPath As String = ConfigurationManager.AppSettings("InvoicePrintAcrobatDir")
	 
	If File.Exists(f_sFilePath) Then
		' (2) Call process
		Process.Start(f_sAcrobatPath, f_sFilePath)
	Else
		lblMessage.ForeColor = Drawing.Color.Red
		lblMessage.Text = "The invoice file does not exist. Cannot preview."
		Exit Sub
	End If
End Sub
.exe File
System.Diagnostics.Process.Start("\\CLEFS1\apps\Carpe\CD32.EXE /I")
Jump to Top
.Net 2.0 : GridView Events
RowCommand
' Page
<asp:ButtonField Text="Void" ButtonType="Link" CommandName="Void" />

' Code Behind
Protected Sub grdMeterCorrection_RowCommand(ByVal sender As Object, ByVal e As 
System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles grdMeterCorrection.RowCommand
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after a ButtonField button in the GridView is clicked.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_iIndex As Integer = Convert.ToInt32(e.CommandArgument)
	Dim f_oSelectedRow As GridViewRow = grdMeterCorrection.Rows(f_iIndex)
	Dim f_oCertIdCell As TableCell = f_oSelectedRow.Cells(11)
	Dim f_sCertId As String = f_oCertIdCell.Text.Trim
	Dim f_oRateAmtLabel As Label = f_oSelectedRow.FindControl("lblRateAmtId")
	Dim f_sRateAmt As String = f_oRateAmtLabel.Text.Trim
 
	If e.CommandName.ToLower = "void" Then
		Dim f_bVoidRet As Boolean = VoidCert(f_sCertId)
	ElseIf e.CommandName.ToLower = "activate" Then
		Dim f_bActivateRet As Boolean = ActivateCert()
	End If
End Sub
RowUpdating
 
Sub grdCustomers_RowUpdating(ByVal o As Object, ByVal e As GridViewUpdateEventArgs) _
Handles grdCustomers.RowUpdating
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires after the Update button is clicked. We need to do some
' validating before updated record is sent to DB.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_oNameTextBox As System.Web.UI.WebControls.TextBox
	f_oNameTextBox = grdCustomers.Rows(e.RowIndex).FindControl("txtName")
	Dim f_sName As String = f_oNameTextBox.Text.Trim
End Sub
RowDataBound
Protected Sub grdCustomers_RowDataBound(ByVal sender As Object, ByVal e As 
System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles grdCustomers.RowDataBound
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' This event fires as the GridView is being constructed (as each row becomes
' databound). Here we check weather or not to disable/enable the Mark Ok
' checkbox.
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	If e.Row.RowType = DataControlRowType.DataRow Then
		If e.Row.Cells(1).Text.Trim.Length > 0 Then
			e.Row.Cells(8).Enabled = False
			
			' another way - using Template/HyperLink 
			'Dim f_oHyperLink As System.Web.UI.WebControls.HyperLink
			'f_oHyperLink = e.Row.Cells(8).FindControl("lnkVolAf")

			'If f_oHyperLink.Text.Trim <> e.Row.Cells(9).Text.Trim Then
				'f_oHyperLink.ControlStyle.ForeColor = Drawing.Color.Red
			'Else
				'f_oHyperLink.ControlStyle.ForeColor = Drawing.Color.Black
			'End If
		End If
	End If
End Sub
Jump to Top
.Net 2.0 : Fields
ButtonField - Page
<asp:ButtonField Text="Void" ButtonType="Link" CommanName="VoidCert" />
ButtonField - Code Behind
Sub grdCerts_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles grdCerts.RowCommand
	' Use the CommandName property to determine which button was clicked.
        If e.CommandName = "VoidCert" Then
		
	End If
End Sub
Jump to Top
.Net 2.0 : Files
Files - Check if exists
Imports System.IO

If File.Exists("C:\Temp\test.txt") Then

End If
Jump to Top
.Net 2.0 : Format
HTMLEncode (always add HtmlEncode="False")
' $148,267.80
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:C}" />
Page
<asp:Label ID="lblAmount" Text='<%# String.Format("{0:C}", Eval("AMOUNT")) %>' runat="server" />
Code
Dim f_cAmount As Decimal = 12.21 
lblMessage.Text = String.Format("{0:C}", f_cAmount)
Align
<asp:TextBox ID="txtAmount" style="TEXT-ALIGN: right" runat="server" />
Numbers
' $148,267.80
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:C}" /> 
 
' 148,267
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###}" /> 
 
' 148,267.8
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###.##}" />

' 148,267.0
<asp:BoundField DataField="VOL" HeaderText="Volume" HtmlEncode="False" DataFormatString="{0:#,###.0}" />
Dates - BoundField
' 12/31/2008
<asp:BoundField DataField="DATE" HeaderText="Date" HtmlEncode="False" DataFormatString="{0:MM/dd/yyyy}" />
Dates - TemplateField
<asp:TemplateField HeaderText="Peak Date">
	<EditItemTemplate>
		<asp:TextBox ID="txtPeakDayEdit" Text='<%# String.Format("{0:MM/dd/yyyy}", Eval("PEAK_DAY")) %>' 
		runat="server" MaxLength="10" Width="70" />
	</EditItemTemplate>   
	<ItemTemplate>
		<asp:Label ID="lblPeakDayRetrieve" Text='<%# String.Format("{0:MM/dd/yyyy}", Eval("PEAK_DAY")) %>' 
		runat="server" />
	</ItemTemplate>
</asp:TemplateField>
Jump to Top
.Net 2.0 : FormView
FindControl
Dim f_oTextBox As TextBox = fmvAgencyInvoice.FindControl("txtWaterAdminApprove")
Jump to Top
.Net 2.0 : GridView
RowUpdating -- exit after update kludge.
lblMessage.Text = "Comment updated."
e.Cancel = True
grdComments.EditIndex = -1
grdComments.DataBind()
Exit Sub
Footer
Protected Sub grdCertified_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
Handles grdCertified.RowDataBound
	If e.Row.RowType = DataControlRowType.Footer Then
		e.Row.Cells(13).ColumnSpan = 3
		e.Row.Cells(13).Text = "Amt Total:"
		e.Row.Cells(13).HorizontalAlign = HorizontalAlign.Right
		e.Row.Cells(14).ColumnSpan = 2
		e.Row.Cells(14).Text = String.Format("{0:C}", Me.CertAmtTotal)
		e.Row.Cells(14).HorizontalAlign = HorizontalAlign.Left
	End If
End Sub
Freeze Columns
More Info: Vishwamohan Blog
' GRIDVIEW
<asp:Panel ID="pnlCustomers" Width="800px" ScrollBars="Horizontal" runat="server">
	<asp:GridView ID="grdCustomers" runat="server">
		<Columns>
			<asp:BoundField DataField="CUST_ID" HeaderText="Customer" 
				ItemStyle-CssClass="StaticColumn" HeaderStyle-CssClass="StaticColumn" />
		</Columns>
	</asp:GridView>
</asp:Panel>
  
                                              
' CSS
.StaticColumn
{      
	background-color:#eeeeee;
	border: none;
	position: relative;
}
Count Rows
If grdComments.Rows.Count > 0 Then
	btnDelete.Enabled = True
End If
EditItemTemplate
<asp:GridView>
	<Columns>
		<asp:templatefield headertext="Name">
			<itemtemplate>
				<asp:label id="FirstName" text= '<%# Eval("fname") %>' runat="server"/>
				<asp:label id="LastName" text= '<%# Eval("lname") %>' runat="server"/>
			</itemtemplate>
			<edititemtemplate>
				<asp:textbox id="Textbox1" text= '<%# Eval("fname") %>' runat="server"/>
				<asp:textbox id="Textbox2" text= '<%# Eval("lname") %>' runat="server"/>
			</edititemtemplate>
		</asp:templatefield>
	</ Columns>
</asp:GridView>
Jump to Top
.Net 2.0 : HashTable
Dim ht as new HashTable()
ht.Add("Number", 10)
ht.Add("Name", "Fred Flintstone")
ht.Add("Age", 40)

lblName.Text = ht.Item("Name")
Jump to Top
.Net 2.0 : HasValue
Dim TotalCertified As Nullable(Of Decimal)
TotalAvail = QueryTA.GetVolAvailableToCertify(CDec(Me.OccurPrdTextBox.Text), Me.ddlAgency.SelectedValue)
If TotalAvail.HasValue Then
	Dim AccountTA As New WINS.DataTier.AccountInfoTableAdapters.WINS_ACCT_CONTRACTTableAdapter
	Dim ContractsCount As Data.DataTable
	ContractsCount = AccountTA.GetOpenContracts(Me.BillAgency , Me.DeliveryAgency, "SSS", Me.OccurPeriod)
	 
	Dim ContractsTA As New WINS.DataTier.AccountInfoTableAdapters.WINS_ACCT_CONTRACTTableAdapter
	Dim ContractsTable As WINS.DataTier.AccountInfo.WINS_ACCT_CONTRACTDataTable = ContractsTA.GetOpenContracts (Me.BillAgency, 
		Me.DeliveryAgency, "SSS", Me.OccurPeriod)
	If ContractsTable.Rows.Count = 0 Then
	
	End If
End If
Jump to Top
.Net 2.0 : HyperLink
HyperLinkField
<asp:HyperLinkField HeaderText="Vol Af" DataTextField="Vol Af" DataNavigateUrlFields="METER_ID,OCCUR_PERIOD" 
	DataNavigateUrlFormatString="DailyRounding.aspx?M={0}&O={1}" Target="_new" />
TemplateField
<asp:TemplateField HeaderText="Volume"> 
	<ItemTemplate> 
		<asp:HyperLink ID="lnkVolume" Text='<%# Eval("volume") %>' NavigateUrl='NewPage.aspx'
			Target="_new" runat="server" /> 
	</ItemTemplate> 
</asp:TemplateField> 
NavigateUrl
<asp:TemplateField HeaderText="Volume"> 
	<ItemTemplate> 
		<asp:HyperLink ID="lnkVolAf" Text='<%# Eval("Volume") %>' NavigateUrl='<%# String.Format(
			"MyPage.aspx?I={0}&P={1}", Eval("ID"), Eval("PERIOD")) %>' Target="_new" runat="server" />
	</ItemTemplate> 
</asp:TemplateField> 
Jump to Top
.Net 2.0 : JavaScript
Popup Window
1. 

' CODE BEHIND (ORIGINAL PAGE)

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles MyBase.Load

	' OBSOLETE: Me.GetPostBackEventReference(Me, String.Empty)
	ClientScript.GetPostBackEventReference(Me, String.Empty)

	If Not Page.IsPostBack Then
		Call SetDefaults()
	Else
		Dim f_sEventTarget As String = IIf((Me.Request("__EVENTTARGET") Is Nothing), String.Empty, _
			Me.Request("__EVENTTARGET"))

		If f_sEventTarget = "PostBackFromChildWindow" Then
			Call BindAllGrids()
		End If
	End If
End Sub

Protected Sub btnMeterCorrection_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnMeterCorrection.Click
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' This event fires after the Meter Correction button is clicked.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	lblMessage.Text = String.Empty

	Dim f_oTextBoxInvNum As TextBox = Me.fmvAgencyInvoice.FindControl("txtInvNum")
	Dim f_oTextBoxInvNumVer As TextBox = Me.fmvAgencyInvoice.FindControl("txtVersion")
	Dim f_oTextBoxBillPeriod As TextBox = Me.fmvAgencyInvoice.FindControl("txtBillPeriod")

	Dim f_sPath As String = "MeterCorrection.aspx?A=" & drpAgencies.SelectedValue & "&I=" & _
	f_oTextBoxInvNum.Text.Trim & "&V=" & f_oTextBoxInvNumVer.Text.Trim & "&B=" & _
	f_oTextBoxBillPeriod.Text.Trim

	Call Popup(f_sPath)
End Sub

Private Sub Popup(ByVal sPath As String)
	Dim lbl As New Label
	lbl.Text = "<script language='javascript'>" & _
		"window.open('" & sPath & "','popupWindow','1000,600,resizable=yes,scrollbars=yes');</script>"
	Page.Controls.Add(lbl)
End Sub

' PAGE (ORIGINAL PAGE)
<asp:LinkButton ID="btnMeterCorrection" Text="Meter Correction" 
ForeColor="#0000ff" CausesValidation="false" runat="server" />

' PAGE (POPUP PAGE)
<asp:LinkButton ID="btnExit" Text="Exit" OnClientClick="window.opener.__doPostBack('PostBackFromChildWindow', ''); 
	window.close(); return false;" runat="server" />
2. 

<asp:LinkButton ID="btnMeterCorrection" Text="Meter Correction" ForeColor="#0000ff" 
CausesValidation="false" runat="server" OnClientClick="javascript:window.open('MeterCorrection.aspx', 
'window_name', 'width=1000, height=600, resizable=yes, scrollbars=yes');" />

OR

Me.btnMeterCorrection.Attributes.Add("onclick",
"javascript:window.open('MeterCorrection.aspx', 'window_name',
'width=1000, height=600, resizable=yes, scrollbars=yes');")
Jump to Top
.Net 2.0 : Nothing
' Integer
If Not f_iBase = Nothing Then

End If

' String
If Not f_sBase Is Nothing Then

End If
Jump to Top
.Net 2.0 : NULL
Data Controls
Data controls support a variety of ways to handle null or missing data. To begin with, 
the GridView, FormView, and DetailsView all support an EmptyDataText or EmptyDataTemplate 
property that you can use to specify a rendering for the control when the data source returns 
no rows of data. Only one of EmptyDataText and EmptyDataTemplate needs to be set 
(EmptyDataTemplate overrides when both are set). You can also specify a ConvertEmptyStringToNull 
property on BoundField (and derived field types), TemplateField or data source parameter objects 
to specify that String.Empty values posted from the client should be converted to null before 
invoking the associated data source operation. ObjectDataSource also supports a ConvertNullToDbNull 
property that can be set to true when the associated method expects DbNull parameters instead of 
null (the TableAdapter classes in a Visual Studio DataSet have this requirement). You can also 
specify a NullDisplayText property on BoundField (and derived field types) to specify a value 
for the field to display when the field value from the data source is returned as null. If this 
value is not changed during edit mode, the value will roundtrip as null back to the data source 
during an Update operation. Lastly, you can also specify a DefaultValue property on data source 
parameters to specify a default value for the parameter when the parameter value passed is null. 
These properties can a chaining effect, for example if both ConvertEmptyStringToNull and DefaultValue 
are set, a String.Empty value will first be converted to null and subsequently to the default value. 
Nullable
Dim f_iCapPercent As Nullable(Of Decimal)
Dim f_oTableAdapter As New BRAVO.DataTier.InvoiceInfoTableAdapters.CUST_POTableAdapter
f_iCapPercent = f_oTableAdapter.GetTier1Cap(vAgency)
If f_iCapPercent.HasValue = True Then
	Return "90%"
Else
	Return "60%"
End If
f_oTableAdapter.Dispose() 
TableAdapter
If you receive an error related to a null value being returned, click on the properties of the 
field and set the NullValue property to (Nothing).
Jump to Top
.Net 2.0 : Object Test Bench
Working with Immediate Window has one major drawback: it requires a lot of typing without any kind of support from the IDE. There is however an alternative way to call your methods using Visual Studio Object Test Bench.
More Info: Problems
(1) Set your project as the StartUp Project.
(2) Switch to Class View.
(3) Select the method. EX: {}Store {}DataTier {}InvoiceInfo.
(4) Right click on method and select: Create Instance : New().
(5) You should see the Object Test Bench window at the bottom. Right click on your instance and
    select: Invoke Method : (select method).
Jump to Top
.Net 2.0 : Page
More Info: MSDN
Life-Cycle
PreInit
Init
InitComplete
PreLoad
Load
Control Events
Load Complete
PreRender
SaveStateComplete
Render
Unload
Jump to Top
.Net 2.0 : Page Methods
More Info: ASP Alliance
Exposing Web Services to client script.
<asp:scriptmanager id="ScriptManager1" runat="server" enablepagemethods="true" />

<body onunload="HandleClose()">

<script language="javascript" type="text/javascript">
  //<![CDATA[
  function HandleClose() 
   {
		if(window.event.clientY < 0 && window.event.clientY < -80)
		{
			PageMethods.DeleteCart();
		}
   }
   //]]>
</script>
Code behind
<WebMethod(EnableSession:=True)> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Xml, _
            XmlSerializeString:=True)> _
    Public Function DeleteCart() As String
        Dim f_bRet As Boolean = False
        f_bRet = DeleteCart()
        If f_bRet = False Then
            Return False
        End If

        Return True
    End Function
Jump to Top
.Net 2.0 : Pagination
Set back to 0 if Retrieve button clicked again.
Protected Sub btnRetrieve_Click(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles btnRetrieve.Click
	grdExclusions.PageIndex = 0
End Sub
Jump to Top
.Net 2.0 : Panel
Hide/Show
Me.Panel1.Style.Item("display") = "none" 
Me.Panel1.Style.Item("display") = ""
Jump to Top
.Net 2.0 : Postback
Check if Postback before processing some javascript.
' PAGE
<script language="javascript">
<!--
var g_isPostBack = false;

window.onbeforeunload = function ()
{
 if( g_isPostBack == true )
  return; // Let the page unload

 if ( window.event )
  window.event.returnValue = 'You will lose any unsaved changes!'; // IE
 else
  return 'You will lose any unsaved changes!'; // FX
}
//-->
</script>

' CODE BEHIND
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
	Handles MyBase.Load
	
    RegisterOnSubmitStatement("OnSubmitScript", "g_isPostBack = true;")
End Sub
Jump to Top
.Net 2.0 : PreRender
Protected Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
	Me.CertSingleVolumeEntry1.EnableEditButtons(Me.CertIDGenerator1.SelectedCertStatus)
	Me.UpdatePanel5.Update()
End Sub
Jump to Top
.Net 2.0 : RegularExpression
More Info: MSDN
Numeric - Integer (positive, no decimal)
<asp:RegularExpressionValidator ID="regRateType" ControlToValidate="txtRateType" ValidationExpression="^\d+$" 
ErrorMessage="Invalid Rate Type. Valid value: 111" runat="server" />
Numeric - Integer (6 digits only)
<asp:RegularExpressionValidator ID="regBillPeriod" ControlToValidate="txtBillPeriod" Font-Size="8pt" 
Display="Dynamic" ErrorMessage="Invalid Bill Period. Valid format: YYYYMM." runat="server" 
ValidationExpression="\d{6}" />	
Numeric - Decimal
<asp:RegularExpressionValidator ID="regAmount" ControlToValidate="txtAmount" Font-Size="8pt" 
Display="Dynamic" ErrorMessage="Invalid Amount. Valid format: 1234567.123456 or 1234567." 
runat="server" ValidationExpression="^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$" />	
Numeric - Decimal
<asp:RegularExpressionValidator ID="regCCFlow" ControlToValidate="txtCCFlow" Font-Size="8pt" 
Display="Dynamic" ErrorMessage="Invalid CC Flow. Valid format: 1234567.12 or 1234567." runat="server" 
ValidationExpression="^\d+(\.\d\d)?$" /> 	
Numeric - Decimal (allow negative)
<asp:RegularExpressionValidator ID="regBillAmount" ControlToValidate="txtBillAmount" Font-Size="8pt" 
Display="Dynamic" ErrorMessage="Invalid Bill Amount. Valid format: 1234567.12 or 1234567." 
runat="server" ValidationExpression="^(-)?\d+(\.\d\d)?$" /> 	
Multiline Length Validation
<%@ Register Assembly="Validators" Namespace="Sample.Web.UI.Compatibility" TagPrefix="cc1" %>

<cc1:RegularExpressionValidator ID="regComments" ControlToValidate="txtComments" Display="Dynamic" 
	ErrorMessage="Maximum length is 30 characters" ValidationExpression=".{0,30}" runat="server" />
Jump to Top
.Net 2.0 : Rounding
Dim f_cExample As Decimal = 4.346

' 4.35
Dim f_cRounded1 As Decimal = Math.Round(f_cExample, 2, MidpointRounding.AwayFromZero)
 
' 4.34
Dim f_cRounded2 As Decimal = Math.Round(f_cExample, 2, MidpointRounding.ToEven)
Jump to Top
.Net 2.0 : String
IndexOf
If f_sReturn.ToUpper.IndexOf("ALREADY EXISTS") <> -1 Then
	'...
End If
Substring
Dim f_sCurrentBPYear As String = Me.CurrentBillPeriod.Substring(0, 4)
Jump to Top
.Net 2.0 : Source Control
Toos|Options|Source Control
Jump to Top
.Net 2.0 : TableAdapter
Check if any rows returned
Dim f_oTableAdapter As New ChargeInfoTableAdapters.CHG_CHARGESTableAdapter
Dim f_oTable As ChargeInfo.CHG_CHARGESDataTable
f_oTable = f_oTableAdapter.GetBaseChargeNull()
If f_oTable.Rows.Count = 0 Then
	e.Row.Cells(12).Enabled = False
Else
	e.Row.Cells(12).Enabled = True
End If
f_oTableAdapter.Dispose()
Grab record values
Dim f_oTableAdapter As New ChargeInfoTableAdapters.RULE_SETTableAdapter
Dim f_oTable As DataTier.ChargeInfo.RULE_SETDataTable = f_oTableAdapter.GetComment(drpNonStandard.SelectedValue)
If Not f_oTable.Rows.Count = 0 Then
	Dim f_oRow As DataTier.ChargeInfo.RULE_SETRow = f_oTable.Rows(0)
	txtComment.Text = f_oRow.DESCR.Trim
End If
f_oTableAdapter.Dispose()
Return string value
Dim f_oOkTableAdapter As New InvoiceInfoTableAdapters.WINS_INV_CRCTableAdapter
Dim f_sOk As String = f_oOkTableAdapter.CCSetupCheckOk(drpAgencies.SelectedValue, f_sStartPeriod, f_sEndPeriod)
If Not f_sOk Is Nothing Then
	If f_sOk.Length > 0 Then
		lblMessage.Text = "An error occurred. The corresponding invoice has already been Ok'd."
		Exit Sub
	End If
End If
f_oOkTableAdapter.Dispose()
Return one value
Dim CurrBillPeriod As Nullable(Of Decimal)
Dim BillPrdTA As New WINS.DataTier.CertificationInfoTableAdapters.QueriesTableAdapter
CurrBillPeriod = BillPrdTA.GetCurrentBillPeriod
If CurrBillPeriod.HasValue = True Then
	Me.CurrentBillPeriod = CurrBillPeriod.Value
Else
	lblMessage.Text = "An error occurred. Current Bill Period was not retrieved from the database."
	Exit Sub
End If
Return count
Dim f_oTableAdapter As New InvoiceInfoTableAdapters.INV_METER_BILLEDTableAdapter
Dim f_iCount As Integer = f_oTableAdapter.GetDisableEnable(f_oTextBoxInvNum.Text.Trim)
If f_iCount > 0 Then
	btnMeterCorrection.Enabled = True
Else
	btnMeterCorrection.Enabled = False
End If
f_oTableAdapter.Dispose()
Process and check return value
Dim f_oTableAdapter1 As New InvoiceInfoTableAdapters.INV_MASTER_CHARGESTableAdapter
Dim f_sReturn1 As String = String.Empty
f_sReturn1 = f_oTableAdapter1.MasterChargesInsert(drpAgencies.SelectedValue)
If f_sReturn1.ToLower = "record inserted" Then
	f_sBillingPeriod = f_sBillingPeriod + 1
Else
	lblMessage.Text = "An error occurred. Please contact support and report the following: " & f_sReturn1
	Exit Sub
End If
Jump to Top
.Net 2.0 : TimeTracker
Install
(1)
RUN
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regsql.exe

(2)
ATTACH DB

EXEC

sp_attach_single_file_db @dbname = 'TimeTracker',
@physname = 'D:\Websites\TimeTracker\App_Data\TimeTracker.mdf'
Jump to Top
.Net 2.0 : Using
You can now write code that uses disposable resources without having to author your own Try/Finally blocks, just like in C#.
Using conn As New SqlConnection(dsn)
  Using cmd As New SqlCommand("SELECT * FROM Employees", conn)
    conn.Open()
      Using rdr As SqlDataReader = cmd.ExecuteReader()
        While rdr.Read()
          Console.WriteLine(rdr(0))
        End While
      End Using
  End Using
End Using
Jump to Top
.Net 2.0 : ValidateRequest
.Net has built in security to prevent HTML tags from being entered into form fields.
' Enable built-in security
<%@ Page Language="VB" CodeFile="Comments.aspx.vb" Inherits="Invoice_Comments" ValidateRequest="true" %>

' Disable and handle manually
<%@ Page Language="VB" CodeFile="Comments.aspx.vb" Inherits="Invoice_Comments" ValidateRequest="false" %>

f_sInvoiceComments = Server.HtmlEncode(f_sInvoiceComments)
Jump to Top
.Net 2.0 : Visual Developer Express
A freeware web development tool that allows developers to evaluate the web development and editing 
capabilities of the other Visual Studio 2008 editions at no charge. Its main function is to create 
ASP.NET websites.
Jump to Top
.Net 2.0 : Web.config
Execution Timeout
<location path="Charges/Process.aspx">
	<system.web>
		<httpRuntime executionTimeout="300000"/>
	</system.web>
</location>
Hide/Show Menu Items
<location path="Invoice/EmailAddresses.aspx">
    <system.web>
      <authorization>
        <allow roles="12bAdmin" />
        <deny users="*" />
      </authorization>
    </system.web>
  </location>
</configuration>
Jump to Top
.Net 2.0 : Website Administration Tool
Administer users, roles, and authorization settings.
URL: http://localhost:3057/asp.netwebadminfiles

Or go to Website/ASP.Net Configuration
Jump to Top
.Net 2.0 : Web Parts
More Info: OnDotNet
Jump to Top
.Net 2.0 : Webservice
Call a web service upon browser close. Page uses a MasterPage so it needs a ScriptManagerProxy.
 
APP_CODE/InvoiceLocking.vb
Imports 12Bravo.DataTier
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ScriptService()> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class InvoiceLocking
    Inherits System.Web.Services.WebService

    <WebMethod(EnableSession:=True)> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Xml, _
            XmlSerializeString:=True)> _
    Public Function UnlockInvoices() As String
        Try
            Dim f_oTableAdapter1 As New InvoiceInfoTableAdapters.WINS_INVTableAdapter
            Dim f_sReturn1 As String = String.Empty
            f_sReturn1 = f_oTableAdapter1.UnlockInvoices()
            If f_sReturn1.ToLower = "record deleted" Then
                Return "True"
            Else
                Return "False"
            End If
        Catch ex As Exception
            Return ex.Message
        End Try
    End Function
End Class
 
Invoice.aspx
<%@ Page Language="VB" MasterPageFile="MasterPage.master" AutoEventWireup="false" CodeFile="Invoice.aspx.vb" 
	Inherits="Invoice_Agency" title="Invoice" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <asp:ScriptManagerProxy ID="ScriptManagerProxy1" runat="server">
        <Services>
            <asp:ServiceReference Path="~/WebServices/InvoiceLocking.asmx" />
        </Services>
    </asp:ScriptManagerProxy>
    <script language="javascript" type="text/javascript">
    //<![CDATA[    
    window.onunload = HandleClose;
    
    function HandleClose() 
    {
        if(window.event.clientY < 0 && window.event.clientY < -80)
	    {
            //alert('Calling Unlock');
            InvoiceLocking.UnlockInvoices();
	    }
    }
    //]]>
    </script>
Jump to Top
.Net 2.0 : XSD File
Rather than calling a function in a .vb file, here is an example of calling a Method built into an .xsd file. The XSD file allows you to add TableAdapters.
Private Sub CommentsGet()
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	' Populate the Comments textbox -- Rule #7.
	'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
	Dim f_oTableAdapter As New ChargeInfoTableAdapters.12B_RULE_SETTableAdapter
	 
	Dim f_oTable As 12Bravo.DataTier.ChargeInfo.12B_RULE_SETDataTable = f_oTableAdapter.GetComment()

	If Not f_oTable.Rows.Count = 0 Then
		Dim f_oRow As 12Bravo.DataTier.ChargeInfo.12B_RULE_SETRow = f_oTable.Rows(0)
		txtComment.Text = f_oRow.DESCR.Trim
	End If
 
	f_oTableAdapter.Dispose()
End Sub
Jump to Top
 
Copyright © 2010 12 Bravo