Tutorial Web Developer Visual Basic 2005
Tutorial Web Developer Visual Basic 2005
Tutorial VISUAL WEB DEVELOPER 2005 Visual Basic incluye programacion aspx tareas aplicaciones arreglos y
Microsoft MS SQL SERVER 2000
I.- PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- INTRODUCCION
2.- MODELO DE SOLUCION
3.- VARIABLES
4.- DECLARACION Y TIPOS DE DATOS
5.- OPERADORES ARITMETICOS
6.- JERARQUIA DE OPERACIONES
7.- PROGRAMACION ORIENTADA OBJETOS
8.- MODELOS PROGRAMACION EN INTERNET
9.- REQUISITOS PROGRAMACION INTERNET
10.- IDE COMPILADOR
11.- PROGRAMACION (1)
12.- PROGRAMACION (2)
13.- PAGINAS HYPERLINK Y LINKBUTTON
APENDICE 1A: OBJETOS PROPIOS HTML
APENDICE 1B: PALABRAS RESERVADAS
APENDICE 1C: OBJETOS WEBCONTROLS
APENDICE 1D: EXTRA WEBCONTROLS
II.- CONTROL DE PROGRAMA
1.- INTRODUCCION
2.- CONTROL DE PROGRAMA
3.- INSTRUCCIONES CONDICIONALES
4.- CONDICIONES SIMPLES
5.- OPERADORES RELACIONALES
6.- INSTRUCCION IF
7.- CONDICIONES COMPUESTAS
8.- INSTRUCCION SELECT CASE
9.- LISTBOX Y DROPDOWNLIST
10.- CHECKBOX Y CHECKBOXLIST
11.- RADIOBUTTON Y RADIOBUTTONLIST
12.- CICLO FOR
13.- CICLO DO WHILE LOOP
14.- CICLO DO LOOP WHILE
15.- CONCLUSIONES DE CICLOS
III.- ARREGLOS
1.- INTRODUCCION
2.- ARREGLOS
3.- ARREGLOS TIPO LISTAS
4.- ARREGLOS TIPO TABLA
5.- LISTAS VISUALES ( LISTBOX )
6.- TABLAS VISUALES (TABLE )
IV.- PROCEDIMIENTOS Y FUNCIONES
1.- PROCEDIMIENTOS
2.- PARAMETROS
3.- VARIABLES LOCALES Y GLOBALES
4.- FUNCIONES
5.- ARREGLOS COMO PARAMETROS
V.- BASES DE DATOS
1.- INTRODUCCION
2.- MODELOS DE ALMACENAMIENTO DE DATOS
3.- TABLAS
4.- TABLAS (CONTINUACION)
5.- ADO NET ACTIVE DATA OBJECT
6.- MS SQL SERVER 2000
7.- SELECCION O DESPLIEGUE
8.- INSERCCION O ADICION DE REGISTROS
9.- BUSQUEDAS
10.- FILTROS
11.- OPERACIONES CON CAMPOS
12.- BAJAS
13.- EDICION DE REGISTROS
14.- GRAFICOS O IMAGENES
APENDICE ADO
Variable(s) de Salida
Rango
BYTE
0-255
INTEGER(%) +-2,147,483,698
SINGLE(!)
3.4E+-38(7 DECIMALES)
DOUBLE(#)
1.8E+308(16 DECIMALES)
CURRENCY
STRING($)
2 BILLONES CHARS
BOOLEAN
TRUE, FALSE
DATE
FECHA
VARIANT
Recordar Tambien que en Visual Basic 2005 toda variable usada en un programa se debera declarar al
principio del programa el formato de declaracion mas sencillo es:
DIM VARIABLE AS TIPO (EJEMPLOS)
DIM ALFA AS INTEGER
DIM ALFA AS LONG, BETA AS LONG
DIM ALFA AS INTEGER, NOMBRE AS STRING
DIM CIUDAD AS STRING * 20, ALFA AS DOUBLE
Observar ultimo caso de ciudad asi de esta manera se consigue una string de tamano definido.
En Visual Basic 2005 un problema comun a lo largo de este curso, es la necesidad de convertir variables
numericas a strings y tambien el problema inverso es decir convertir strings a su representacion numerica.
Para este ultimo problema por ejemplo se tiene:
DIM ALFA AS STRING
ALFA = 3.1416
Como se observa del ejemplo anterior, se puede dar en algun momento la necesidad de convertir la string
ALFA a su valor numerico, para resolver este problema se deberan usar las siguientes funciones de
conversion numerica que proporciona visual basic 2005.
Action
Language element
Chr, ChrW
DateSerial, DateValue
Hex, Oct
Number to string.
Format, Str
CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CSng, CShort, CStr,
CType, Fix, Int
Asc, AscW
String to number.
Val
TimeSerial, TimeValue
Suma
Resta
Multiplicacion
Division Flotante
Division Entera
Potencia
MOD
Modulo
se resuelve como:
= 5^8/3
= 9^1/2
En Visual Basic 2005 el operador (MOD) devuelve el residuo entero de una division entre enteros, ejemplo:
Dim alfa As Single;
Alfa = 23 MOD 4;
Desplegar alfa; El resultado en pantalla es 3
Otro ejemplo;
Alfa = 108 MOD 10;
Desplegar alfa; - El resultado en pantalla es 8
TAREAS PROGRAMACION VISUAL BASIC 2005
detectar
detectar
click
maximizar(), cerrar()
dblclk
minimizar(), etc
Un Programa visual web developer 2005 Visual Basic se puede considerar como un conjunto de una o mas
paginas o formas donde cada una de ellas contiene un conjunto de objetos, componentes o controles.
Un componente o propiamente dicho un control es un objeto que se especializa en una tarea especifica por
ejemplo hay controles especializados en desplegar textos o mensajes, otros controles se especializan en
desplegar imagenes o videos, otros en manipular directorios o archivos en disco, etc.
Pero en general tanto las formas como los controles no dejan de ser objetos en programacion y por tanto
tienen sus propiedades, metodos y estan sujetos a eventos.
Usar Ahora la opcion FILE NEW WEB SITE y seleccionar EMPTY WEB SITE.
* Abajo en LOCATION seleccionar FTP.
* Al lado escribir TU SERVIDOR DE FTP (ya lo tienes con LUNARPAGES ver tema anterior) y recordar que se
escribe como FTP:tudominio.com * En LANGUAGE seleccionar Visual Visual Basic Se tiene ahora la siguiente
pantalla.
Click
en
OK
tu
servidor
pide
user
login
con:
OK se tendra
existing
ahora:
Web
Site
click
OK
sigue:
Open
Esta
es la pantalla principal del visual webs developer 2005 y el projecto ha sido creado exitosamente FELICIDADES.
Usar ahora la opcion arriba WEBSITE> ADD NEW ITEM y se tendra ahora la siguiente pantalla:
NOTA SI MANDA UN ERROR ACERCA DE NO PODER IMPORTAR DEFAULT.ASP USAR COPIA LOCAL Seleccionar WEB
FORM y Language = VISUAL Visual Basic. Observar el monton de proyectos diferentes que se pueden crear con
visual web developer 2005 y aqui en programacionfacil.com se crearan nuevos cursos y tutoriales alrededor de
ellos estarse pendiente. Click en ADD y se tendra ahora la PAGINA CENTRAL o INICIAL DEL PROYECTO como lo
muestra
la
siguiente
pantalla:
Poner atencion a
las dos pestanitas abajo de DESIGN y SOURCE que es algo importante. Ahora al IDE le agregamos los tres
siguientes elementos, usando las opciones: VIEW Properties Windows (ventanilla de PROPIEDADES de los
OBJETOS) IEW Solution Explorer (ventanilla de Administracion del Proyecto) VIEW ToolBox (ventanilla de
HERRAMIENTAS) Observar que existen otras VISTAS (VIEW'S) que se usaran mas adelante en el curso. Se tiene
ahora:
Sus
elementos basicos son: 1.- La barra de menus (file, edit , etc.); 2.- La barra de herramientas(icono de grabar, run,
forma, etc.) 3.- La barra o paleta de componentes (TOOLBOX) 4.- La ventana de Propiedades (Windows
Properties) 5.- El Administrador de proyectos (Solution Explorer) 5.- La PAGINA WEB activa o principal
(DEFAULT.ASPX) Es sobre esta ultima forma donde se construira el programa y esta forma se convertira en una
pagina web al momento de ejecutarse el programa. Es decir sera la primera pagina que el usuario ve al momento
de ejecutarse el programa. Esta pagina o forma o ventana es un objeto de Visual Web Developer 2005
Visual Basic y como todos los objetos de Visual Basic y del universo, la forma o ventana tiene asociados
propiedades y eventos. Propiedades son todas las caracteristicas particulares que diferencian un objeto de otro
objeto, las propiedades o caracteristicas mas comunes son forma, tamano, color, etc., para objetos en Visual Web
Developer Visual Basic 2005, estas propiedades se modifican o individualizan usando la ventana de propiedades,
ForeColor
Height
ID
TabIndex
ToolTip
Visible
Width
Interesante verdad?
PROYECTO COMPLETO
1.- Preparar el proyecto tal como se dejo hasta el final del tema anterior, es decir la pantalla inicial es:
<script runat="server">
</script>
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div>
</div>
</form>
</body>
</html>
En particular:
1.- Empieza definiendo el lenguaje de programacion a usar es decir la pagina estara en un servidor de
paginas y es el servidor quien tendra que compilar esta pagina ( recordar que aspx es en realidad un
programa que mezcla instrucciones de dos lenguajes de programacion HTML y Visual Basic) por tanto el
servidor tendra que compilar.
2.- Recordar que este curso esta enfocado a aprender el lenguaje de programacion VISUAL Visual Basic y a
ustedes les toca aprender por su cuenta el lenguaje de programacion HTML de los cuales existen muchos
tutoriales en el WEB.
3.- La segunda parte que contiene DEFAULT.ASPX son los tags o marcadores <script> ... </script> es
dentro de estos tags donde se pondra el codigo en visual Visual Basic.
4.- La tercera parte esta encerrada entre tags <html>..</html> esta parte enciera el codigo del lenguaje
HTML y estos tags le indican al servidor que empieze a construir una pagina web para enviarsela a algun
usuario que la este pidiendo.
5.- La siguiente parte inportantes esta
VENTANA VIRTUAL dentro de la PAGINA
labels, textboxs, buttons) y estos objetos
objetos deberan ir dentro de una FORMA o
6.- Los tags e instrucciones head, body, div son instrucciones de HTML y recordar que HTML lo estudian por
su cuenta en algun tutorial de HTML.
7.- EN RESUMEN SE ESTA CONSTRUYENDO UNA PAGINA ASPX QUE CONTIENE UNA PAGINA
<HTML>..</HTML> QUE A SU VEZ CONTIENE UNA VENTANA O FORMA VIRTUAL <FORM>
</FORM> QUE A SU VEZ CONTENDRA LOS OBJETOS WEBCONTROLS (LABELS, TEXTBOXS,
BUTTONS) NECESARIOS PARA RESOLVER EL PROBLEMA PLANTEADO.
APARTE LA PAGINA ASPX LLEVA UN APARTADO <SCRIPT></SCRIPT> QUE CONTENDRA EL CODIGO EN
VISUAL BASIC (GENERALMENTE UN EVENTO(RECORDAR TEMA DE OBJETOS) DE ALGUN COMPONENTE
WEBCONTROL.
PROYECTO
USAR la pestanita de DESIGN y arrastrar desde TOOLBOX un LABEL, dos TEXTBOX y un BUTTON.
En PROPIEDADES, usando tecla TAB moverse a LABEL y en propiedad ID cargarle MESES, con TAB irse a los
TEXTBOX y en propiedades ID cargarles con BASE1(no se puede usar BASE porque es palabra reservada de
visual basic) y ALTURA, al final con tab irse a BUTTON y en la ventanita de propiedades usar el icono de
EVENTOS(ver tema anterior) y buscar el evento buttonclick y cargarlo con la palabra EVENTO1.
Si en alguna parte de este proceso terminan en la pantalla de codigo, regresar a la pantalla de diseno
usando la pestanita de abajo que dice DESIGN y recordar que estas dos pestanitas de SOURCE y DESIGN
les permite estar circulando entre diseno y codigo.
PROGRAMA
<script runat="server">
End Sub
</script>
<head runat="server">
</head>
<body>
</body>
</html>
DE ARRIBA
<script runat="server">
End Sub
</script>
<head runat="server">
</head>
<body>
</form>
</body>
</html>
Notas:
1.- Solo escribir lo morado y creo que para el siguiente programa ejemplo ya deberan identificar cuales
partes se agregan al default ( solo el evento y los controles asp:)
2.- no hay notas nuevas.
3.- Observar que ToString(string de formato) puede incluir una mascarilla de formato que puede usar los
siguientes caracteres:
Character Description
None
(0)
Digit placeholder. Displays a digit or a zero. If the 2005ion has a digit in the position
where the zero appears in the format string, display it; otherwise, displays a zero in
that position. If the number has fewer digits than there are zeros (on either side of the
decimal) in the format 2005ion, displays leading or trailing zeros. If the number has
more digits to the right of the decimal separator than there are zeros to the right of the
decimal separator in the format 2005ion, rounds the number to as many decimal places
as there are zeros. If the number has more digits to the left of the decimal separator
than there are zeros to the left of the decimal separator in the format 2005ion, displays
the extra digits without modification.
(#)
Digit placeholder. Displays a digit or nothing. If the 2005ion has a digit in the position
where the # character appears in the format string, displays it; otherwise, displays
nothing in that position. This symbol works like the 0 digit placeholder, except that leading
and trailing zeros aren't displayed if the number has fewer digits than there are # characters
(.)
Decimal placeholder. The decimal placeholder determines how many digits are
displayed to the left and right of the decimal separator. If the format 2005ion contains
only # characters to the left of this symbol; numbers smaller than 1 begin with a
decimal separator. To display a leading zero displayed with fractional numbers, use
zero as the first digit placeholder to the left of the decimal separator. In some locales,
a comma is used as the decimal separator. The actual character used as a decimal
placeholder in the formatted output depends on the number format recognized by your
system. Thus, You should use the period as the decimal placeholder in your formats
even if you are in a locale that uses a comma as a decimal placeholder. The formatted
string will appear in the format correct for the locale.
(%)
Percent placeholder. Multiplies the 2005ion by 100. The percent character (%) is
inserted in the position where it appears in the format string.
(,)
(:)
Time separator. In some locales, other characters may be used to represent the time
separator. The time separator separates hours, minutes, and seconds when time values
are formatted. The actual character used as the time separator in formatted output is
determined by your system settings.
(/)
Date separator. In some locales, other characters may be used to represent the date
separator. The date separator separates the day, month, and year when date values
are formatted. The actual character used as the date separator in formatted output is
determined by your system settings.
Scientific format. If the format 2005ion contains at least one digit placeholder (0 or #)
to the left of E-, E+, e-, or e+, the number is displayed in scientific format and E or e is
inserted between the number and its exponent. The number of digit placeholders to
(E- E+ ethe left determines the number of digits in the exponent. Use E- or e- to place a minus
e+)
sign next to negative exponents. Use E+ or e+ to place a minus sign next to negative
exponents and a plus sign next to positive exponents. You must also include digit
placeholders to the right of this symbol to get correct formatting.
-+$()
Literal characters. These characters are displayed exactly as typed in the format string.
To display a character other than one of those listed, precede it with a backslash (\) or
enclose it in double quotation marks ( ).
(\)
Displays the next character in the format string. To display a character that has special
meaning as a literal character, precede it with a backslash (\). The backslash itself
isn't displayed. Using a backslash is the same as enclosing the next character in double
quotation marks. To display a backslash, use two backslashes (\\). Examples of
characters that can't be displayed as literal characters are the date-formatting and timeformatting characters (a, c, d, h, m, n, p, q, s, t, w, y, /, and :), the numeric-formatting
characters (#, 0, %, E, e, comma, and period), and the string-formatting characters (@, &, <,
>, and !).
(ABC)
Displays the string inside the double quotation marks ( ). To include a string in the
style argument from within code, you must use Chr(34) to enclose the text (34 is the
character code for a quotation mark ()).
<script runat="server">
</script>
<head runat="server">
<title>PRIMERA PAGINA</title>
</head>
<body>
<br />
<br />
</form>
</body>
</html>
Notas:
0.- USAR EL DISEnADOR PARA ARRASTRAR DESDE TOOLBOX LOS CONTROLES APROPIADOS.
1.- No se ocupo el EVENTO que va dentro del <script></script> porque esta pagina no incluye un
programa.
2.- Por supuesto que en las tareas ustedes si tendran que usar el EVENTO porque cada una de las paginas
que construyan deberan resolver un problema de programacion y recordar QUE LO QUE SE PERMITE AL
MAESTRO, NO SE PERMITE AL ALUMNO ;)
<script runat="server">
</script>
<head runat="server">
<title>SEGUNDA PAGINA</title>
</head>
<body>
<br />
<br />
<br />
</form>
</body>
</html>
NOTAS:
1.- Otra vez no se usa programa o script, eso es la tarea.
2.- Se uso un componente IMAGE para desplegar la imagen y observar con cuidado como se carga su
propiedad IMAGEURL.
3.- La imagen jpg deben subirla a su sitio con algun programa de ftp, pueden usar el ftp del explorer ( solo
ftp://tidominioenLUNARPAGES) y explorer les
pongan la siguiente direccion en el internetexplorer
preguntara el login y paswword, ya dentro de sus sitio, solo arrastrar la imagen desde tu disco duro a tu
sitio.
Les recomiendo el ftpexplorer que lo pueden bajar gratis desde
no se desactive.
Pero lo importante aqui es recordar que NET FRAMEWORK o TOOLBOX contiene un conjunto muy grande de
componentes utiles para la construccion de programas o aplicaciones y que en este curso no se usaran mas
que algunos de los mas importantes, el resto de ellos deberan estudiarlos, analizarlos y emplearlos por su
cuenta.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic:
1.- Construir la primera PAGINA1.ASPX con tres botones que active cada quien su propia ventana, la
segunda pagina calcula el area de un circulo, la tercera pagina convierte libras a kilogramos y la tercera
AddressOf
Alias
And
AndAlso
Ansi
As
Assembly
Auto
Boolean
ByRef
Byte
ByVal
Call
Case
Catch
CBool
CByte
CChar
CDate
CDec
CDbl
Char
CInt
Class
CLng
CObj
Const
CShort
CSng
CStr
CType
Date
Decimal
Declare
Default
Delegate
Dim
DirectCast
Do
Double
Each
Else
ElseIf
End
Enum
Erase
Error
Event
Exit
#ExternalSource False
Finally
For
Friend
Function
Get
GetType
GoTo
Handles
If
Implements
Imports
In
Inherits
Integer
Interface
Is
Let
Lib
Like
Long
Loop
Me
Mod
Module
MustInherit
MustOverride
MyBase
MyClass
Namespace
New
Next
Not
Nothing
NotInheritable NotOverridable
Object
On
Option
Optional
Or
OrElse
Overloads
Overridable
Overrides
ParamArray
Preserve
Private
Property
Protected
Public
RaiseEvent
ReadOnly
ReDim
#Region
REM
RemoveHandler
Resume
Return
Select
Set
Shadows
Shared
Short
Single
Static
Step
Stop
String
Structure
Sub
SyncLock
Then
Throw
To
True
Try
TypeOf
Unicode
Until
Variant
When
While
With
WithEvents
WriteOnly
Xor
#Const
#ExternalSource
#IfThen#Else #Region
&
&=
*=
/=
\=
^=
+=
-=
Note Variant and Let are retained as keywords, although they are no longer used in Visual Basic .NET.
Fuente: microsoft net
WEBCONTROLS
System.Web.UI.WebControls Namespace
See Also
.NET Framework Class Library
The System.Web.UI.WebControls namespace is a collection of classes that allow you to create Web
server controls on a Web page. Web server controls run on the server and include form controls
such as buttons and text boxes. They also include special purpose controls such as a calendar.
Because Web server controls run on the server, you can programmatically control these elements.
Web server controls are more abstract than HTML server controls. Their object model does not
necessarily reflect HTML syntax.
Namespace hierarchy
Classes
Class
Description
AdCreatedEventArgs
AdRotator
BaseCompareValidator
BaseDataList
Serves as the abstract base class for data listing controls, such as
the DataList and DataGrid. This class provides the methods and
properties common to all data listing controls.
BaseValidator
BoundColumn
Button
ButtonColumn
A column type for the DataGrid control that contains a userdefined command button, such as Add or Remove, that
corresponds with each row in the column.
Calendar
CalendarDay
CheckBox
Displays a check box that allows the user to select a true or false
condition.
CheckBoxList
CommandEventArgs
CompareValidator
Compares the value entered by the user into an input control with
the value entered into another input control or a constant value.
CustomValidator
DataGrid
A data bound list control that displays the items from data source
in a table. The DataGrid control allows you to select, sort, and
edit these items.
DataGridColumn
Serves as the base class for the different column types of the
DataGrid control.
DataGridColumnCollection
DataGridCommandEventArgs
Provides
data
for
the
CancelCommand, DeleteCommand,
EditCommand, ItemCommand, and UpdateCommand events of the
DataGrid control. This class cannot be inherited.
DataGridItem
DataGridItemCollection
DataGridItemEventArgs
DataGridPageChangedEventArgs
DataGridPagerStyle
Specifies the style for the pager of the DataGrid control. This class
cannot be inherited.
DataGridSortCommandEventArgs
DataKeyCollection
DataList
DataListCommandEventArgs
Provides
data
for
the
CancelCommand, DeleteCommand,
EditCommand, ItemCommand, and UpdateCommand events of the
DataList control. This class cannot be inherited.
DataListItem
DataListItemCollection
DataListItemEventArgs
DayRenderEventArgs
DropDownList
EditCommandColumn
A special column type for the DataGrid control that contains the
Edit command buttons for editing data items in each row.
FontInfo
FontNamesConverter
FontUnitConverter
HyperLink
HyperLinkColumn
HyperLinkControlBuilder
Image
ImageButton
Label
LabelControlBuilder
LinkButton
LinkButtonControlBuilder
ListBox
ListControl
ListItem
ListItemCollection
ListItemControlBuilder
Literal
LiteralControlBuilder
MonthChangedEventArgs
PagedDataSource
Panel
PlaceHolder
PlaceHolderControlBuilder
RadioButton
RadioButtonList
RangeValidator
RegularExpressionValidator
Repeater
RepeaterCommandEventArgs
RepeaterItem
RepeaterItemCollection
RepeaterItemEventArgs
RepeatInfo
RequiredFieldValidator
SelectedDatesCollection
ServerValidateEventArgs
Style
Table
TableCell
TableCellCollection
TableCellControlBuilder
TableHeaderCell
TableItemStyle
TableRow
TableRowCollection
TableStyle
Represents the style for a table control. This class is primarily used
by control developers.
TargetConverter
TemplateColumn
Represents a column type for the DataGrid control that allows you
to customize the layout of controls in the column.
TextBox
TextBoxControlBuilder
UnitConverter
ValidatedControlConverter
ValidationSummary
WebColorConverter
WebControl
Serves as the base class that defines the methods, properties and
events common to all controls in the System.Web.UI.WebControls
namespace.
Xml
Interfaces
Interface
Description
IRepeatInfoUser
Defines the properties and methods that must be implemented by any list control
that repeats a list of items.
Structures
Structure Description
FontUnit
Unit
Delegates
Delegate
Description
AdCreatedEventHandler
CommandEventHandler
DataGridCommandEventHandler
DataGridItemEventHandler
DataGridPageChangedEventHandler
DataGridSortCommandEventHandler
DataListCommandEventHandler
DataListItemEventHandler
DayRenderEventHandler
MonthChangedEventHandler
RepeaterCommandEventHandler
RepeaterItemEventHandler
ServerValidateEventHandler
Enumerations
Enumeration
Description
BorderStyle
ButtonColumnType
CalendarSelectionMode
DayNameFormat
Specifies the display format for the days of the week on a Calendar
control.
FirstDayOfWeek
Specifies the day to display as the first day of the week on the
Calendar control.
FontSize
GridLines
Specifies the grid line styles for controls displaying items in a table
structure.
HorizontalAlign
ImageAlign
ListItemType
ListSelectionMode
NextPrevFormat
Represents the display format for the previous and next month
navigation controls within the Calendar.
PagerMode
PagerPosition
RepeatDirection
RepeatLayout
TextAlign
TextBoxMode
TitleFormat
Specifies the title format for the displayed month in the Calendar
control.
UnitType
ValidationCompareOperator
comparison
operators
used
by the
ValidationDataType
ValidationSummaryDisplayMode
ValidatorDisplay
VerticalAlign
display
mode
used
by the
See Also
.NET Framework Class Library
FUENTE: c 2001 Microsoft Corporation. All rights reserved.
Como se puede apreciar existen muchos nuevos objetos de mucha utilidad para la construccion de
sistemas de informacion, todos estos objetos tienen sus propiedades especificas, sin embargo
muchos de ellos comparten las siguientes propiedades:
PROPIEDAD DESCRIPCION
BackColor
ForeColor
Height
ID
TabIndex
ToolTip
Visible
Width
Namespace
AdCreatedEventArgs
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
Displays an advertisement banner on a Web page.
For a list of all members of this type, see AdRotator Members.
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.AdRotator
Namespace
AdCreatedEventArgs
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
Displays an advertisement banner on a Web page.
For a list of all members of this type, see AdRotator Members.
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.AdRotator
[Visual Basic]
**Public Class AdRotator
Inherits WebControl
**[Visual Basic]
**public class AdRotator : WebControl
**[C++]
**public __gc class AdRotator : public WebControl
**[JScript]
**public class AdRotator extends WebControl**
Thread Safety
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded
operations. Any instance members are not guaranteed to be thread safe.
Remarks
Use the AdRotator control to display a randomly selected advertisement banner on the Web
page. The displayed advertisement can change whenever the page refreshes.
Advertisement information is stored in a separate XML file. The XML file allows you to maintain a
list of advertisements and their associated attributes. Attributes include the path to an image to
display, the URL to link to when the control is clicked, the alternate text to display when the
image in not available, a keyword, and the frequency of the advertisement.
As an alternative source of data to an XML file, it is possible to provide advertisement information
through a call-back event. This event can also be used in combination with the XML file to extend
the behavior of the AdRotator control, such as redirecting to another page. See the
AdvertisementFile property for additional information on the file format.
A new advertisement is selected whenever the Web page refreshes. An Impressions attribute can
be assigned to each advertisement. It controls how often an advertisement is selected relative to
the other advertisements in the advertisement file.
Requirements
Namespace: System.Web.UI.WebControls
Calendar Class
See Also
Calendar Members | System.Globalization Namespace | DateTime | DateTimeFormatInfo |
GregorianCalendar | HebrewCalendar | HijriCalendar | JapaneseCalendar | JulianCalendar |
KoreanCalendar | TaiwanCalendar | ThaiBuddhistCalendar
Requirements
Namespace: System.Globalization
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP
Home Edition, Windows XP Professional, Windows .NET Server family
Assembly: Mscorlib (in Mscorlib.dll)
Represents time in divisions, such as weeks, months, and years.
For a list of all members of this type, see Calendar Members.
System.Object
System.Globalization.Calendar
Derived classes
[Visual Basic]
<Serializable>
**MustInherit Public Class Calendar
**[Visual Basic]
[Serializable]
**public abstract class Calendar
**[C++]
[Serializable]
**public __gc __abstract class Calendar
**[JScript]
**public
**Serializable
**abstract class Calendar**
Thread Safety
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded
operations. Any instance members are not guaranteed to be thread safe.
Remarks
A calendar divides time into measures, such as weeks, months, and years. The number, length,
and start of the divisions vary in each calendar.
Any moment in time can be represented as a set of numeric values using a particular calendar. For
example, the last vernal equinox occurred at (0.0, 0, 46, 8, 20, 3, 1999) in the Gregorian
calendar. An implementation of Calendar can map any DateTime value to a similar set of numeric
values, and DateTime can map such sets of numeric values to a textual representation (for
example, 8:46 AM March 20th 1999 AD for the English (United States) culture) using
DateTimeFormatInfo.
A Calendar implementation can define one or more eras. The Calendar class identifies the eras as
enumerated integers where the current era (CurrentEra) has the value 0.
In order to make up for the difference between the calendar year and the actual time that the
earth rotates around the sun or the actual time that the moon rotates around the earth, a leap
year has a different number of days than a standard calendar year. Each Calendar implementation
defines leap years differently.
For consistency, the first unit in each interval (for example, the first month) is assigned the value
1.
The System.Globalization namespace includes the following Calendar
GregorianCalendar,
HebrewCalendar,
HijriCalendar,
JapaneseCalendar,
KoreanCalendar, TaiwanCalendar, and ThaiBuddhistCalendar.
implementations:
JulianCalendar,
Requirements
Namespace: System.Globalization
Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP
Home Edition, Windows XP Professional, Windows .NET Server family
Assembly: Mscorlib (in Mscorlib.dll)
See Also
Calendar Members | System.Globalization Namespace | DateTime | DateTimeFormatInfo |
GregorianCalendar | HebrewCalendar | HijriCalendar | JapaneseCalendar | JulianCalendar |
KoreanCalendar | TaiwanCalendar | ThaiBuddhistCalendar
c 2001 Microsoft Corporation. All rights reserved.
HyperLink Class
See Also
HyperLink Members | System.Web.UI.WebControls Namespace
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
A control that displays a link to another Web page.
For a list of all members of this type, see HyperLink Members.
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.HyperLink
[Visual Basic]
**Public Class HyperLink
Inherits WebControl
**[Visual Basic]
**public class HyperLink : WebControl
**[C++]
**public __gc class HyperLink : public WebControl
**[JScript]
**public class HyperLink extends WebControl**
Thread Safety
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded
operations. Any instance members are not guaranteed to be thread safe.
Remarks
Use the HyperLink control to create a link to another Web page. The HyperLink control is
typically displayed as text specified by the Text property. It can also be displayed as an image
specified by the ImageUrl property.
Note If both the Text and ImageUrl properties are set, the ImageUrl property takes
precedence. If the image is unavailable, the text in the Text property is displayed. In browsers
that support ToolTip functionality, the Text property also becomes the ToolTip.
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
See Also
HyperLink Members | System.Web.UI.WebControls Namespace
c 2001 Microsoft Corporation. All rights reserved.
ImageButton Class
See Also
ImageButton Members | System.Web.UI.WebControls Namespace | Button | Image
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
A control that displays an image and responds to mouse clicks on the image.
For a list of all members of this type, see ImageButton Members.
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.Image
System.Web.UI.WebControls.ImageButton
[Visual Basic]
**Public Class ImageButton
Inherits Image
Implements IPostBackDataHandler, IPostBackEventHandler
**[Visual Basic]
**public class ImageButton : Image, IPostBackDataHandler,
IPostBackEventHandler
**[C++]
**public __gc class ImageButton : public Image, IPostBackDataHandler,
IPostBackEventHandler
**[JScript]
**public class ImageButton extends Image implements
IPostBackDataHandler, IPostBackEventHandler**
Thread Safety
Any public static (Shared in Visual Basic) members of this type are safe for multithreaded
operations. Any instance members are not guaranteed to be thread safe.
Remarks
Use the ImageButton control to display an image that responds to mouse clicks.
Both the Click and Command events are raised when the ImageButton control is clicked.
By using the OnClick event handler, you can programmatically determine the coordinates where
the image is clicked. You can then code a response, based on the values of the coordinates. Note
the origin (0, 0) is located at the upper left corner of the image.
You can use the OnCommand event handler to make the ImageButton control behave like a
command button. A command name can be associated with the control by using the
CommandName property. This allows multiple ImageButton controls to be placed on the same
Web page. The value of the CommandName property can then be programmatically identified in
the OnCommand event handler to determine the appropriate action to perform when each
ImageButton control is clicked. The CommandArgument property can also be used to pass
additional information about the command, such as specifying ascending order.
Requirements
Namespace: System.Web.UI.WebControls
Platforms: Windows 2000, Windows XP Professional, Windows .NET Server family
Assembly: System.Web (in System.Web.dll)
See Also
ImageButton Members | System.Web.UI.WebControls Namespace | Button | Image
c 2001 Microsoft Corporation. All rights reserved.
condicion, por ejemplo si se capturo 6000 en sueldo en el ejemplo a) entonces el computador indicaria que
la condicion es CIERTA pero en otro caso si a la variable sueldo primero se le asigno un valor de 250
entonces el computador indicaria que la condicion es FALSA.
Ya dependiendo del resultado de la evaluacion, el computador ejecuta las instrucciones contenidas en el
grupo de cierto o falso respectivamente.
En VISUAL WEB DEVELOPER 2005 Visual Basic empezamos el analisis por la CONDICION.
sueldo
>
300,000
En VISUAL WEB DEVELOPER 2005 Visual Basic una condicion simple se define como el conjunto de variables
y/o constantes unidas por los llamados operadores relacionales.
Igual que
>
Mayor que
<
Menor que
>=
<>
a) icono run
b) start without debugging
c)
http://usuario.dotnet29.hostbasket.com/prog100.aspx
Programa:
Notas:
En cuanto al if se esta respetando el formato que ya se indico.
Lo nuevo es que existen tres tipos de objetos o controles de orden o comando, ellos son BUTTON,
LINKBUTTON, IMAGEBUTTON (efectivamente si hacen click dentro de la imagen de mi perrito (osito) se
activa el metodo correspondiente y por tanto se evalua la condicion.
En cuanto a button y linkbutton el primero es la cajita normal de ordenes que se a venido usando y el
segundo es una liga normal de html, observar que pueden usar el mismo ONCLICK y evento1.
Pero imagebutton debe llevar su propio onclick y en su metodo evento1 no se manda como parametro un
EVENTARGS sino un IMAGECLICKEVENTARGS.
Recordar que en visual web developer Visual Basic es valido usar mas de una instruccion dentro del grupo
cierto o falso del if.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Capturar un numero cualesquiera e informar si es o no es mayor de 100 ( programar los dos modelos y
usar button's diferentes)
2.- Capturar un numero entero cualesquiera e informar si es o no es multiplo de 4 ( recordar el operador
mod(%), analizado en el tema de operadores aritmeticos).
3.- Capturar los cinco datos mas importantes de un Empleado, incluyendo el sueldo diario y los dias
trabajados desplegarle su cheque semanal solo si gano mas de $500.00 en la semana, en caso contrario
desplegarle un bono de despensa semanal de $150.00.
4.- Capturar los datos mas importantes de un estudiante incluyendo tres calificaciones construir una boleta
de calificaciones en una pagina de respuesta bien bonita si el estudiante es de la carrera de medicina, en
caso contrario construir una pagina mas bonita todavia que despliega un oficio citando a los padres del
Y LOGICO
OR
O LOGICO
NOT
NEGACION
Para que el computador evalue como CIERTA una condicion compuesta que contiene el operador logico
AND, las dos condiciones simples deben ser ciertas.
Para que el computador evalue como CIERTA una condicion compuesta que contiene el operador logico
OR, basta con que una de las condiciones simples sea cierta.
La cantidad total de casos posibles cuando se unen dos o mas condiciones simples esta dada por la relacion
donde n = cantidad de condiciones, la primera mitad de ellos empieza en cierto y la segunda mitad en
falso.
Ejemplo, si formamos una condicion compuesta con dos condiciones simples y el operador logico y, la
cantidad total de casos posibles serian
La evaluacion final, se obtiene usando la regla anteriormente descrita para una condicion compuesta, que
contiene el operador AND.
Esta tabla significa lo siguiente:
1.- Cualquiera que sean la cantidad de datos procesados, siempre caera en uno de estos cuatro casos
generales.
La tabla de verdad para una condicion compuesta con OR es la siguiente:
IRA COND SIMPLE 2DA COND SIMPLE EVALUACION
C
Construir una tabla de verdad para una condicion compuesta de tres o mas condiciones simples es tambien
tarea sencilla, solo recordar que;
2.- Para evaluar esta condicion triple primero se evaluan las dos primeras incluyendo su operador bajo las
reglas ya descritas y luego se evalua el resultado parcial contra la ultima condicion y ultimo operador para
obtener la evaluacion final.
Ejemplo una condicion compuesta de tres condiciones simples, donde el primer operador logico es el AND
y el segundo operador logico es el OR, daria la siguiente tabla de verdad.
Ira cond 2da cond Eval 1a AND 2a 3ra cond Eval eval OR 3ra
C
PROGRAMA EJEMPLO
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
Protected Sub EVENTO1(ByVal sender As Object, ByVal e As System.EventArgs)
If EDAD.Text < 30 And SEXO.Text = "H" Then
Label1.Text = "MUCHACHO JOVEN"
Else
Label1.Text = "PROFESOR VIEJO"
End If
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>PROGRAMACION VISUAL BASIC ASPX</title>
</head>
<body>
<form id="form1" runat="server">
EDAD<ASP:TEXTBOX ID=EDAD RUNAT=SERVER/><BR>
SEXO<ASP:TEXTBOX ID=SEXO RUNAT=SERVER/><BR>
<ASP:BUTTON ID="BUTTON1" TEXT=OK ONCLICK=EVENTO1 RUNAT=SERVER/><BR>
RESULTADO:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
Observar que las condiciones simples se unen con el operador logico AND.
Corrida:
Tomar en cuenta es que se pueden usar mas de dos instrucciones en cada case.
Observar el caso b, observar como se pueden usar mas de dos case, sorry por lo de BACA pero el unico
animalito que me acorde fue el BURRO y luego mis alumnos se sienten aludidos y ofendidos.
Observar en caso c como se encadenan dos o mas strings usando el simbolo ampersand (&)
RECORDAR USAR EL DISEnADOR (DESIGN) PARA DARLE MEJOR PRESENTACION.
Corrida:
Observar que tanto en ListBox como en DropDownList se cargan sus elEmentos con LISTITEM.
Ya en codigo se usa la propiedad SelectedItem, que esta apuntando o cargada con el valor o datos
seleccionado por el usuario.
La diferencia en pantalla o ejecucion entre ambos controles, se ve en la corrida que esta unos parrafos mas
abajo.
Recordar que estos controles tienen muchas propiedades muy utiles y que se seguiran usando a lo largo del
curso.
Corrida:
Solo agregar un ID al control y un listitem por cada elemento, para programarlo solo usar la propiedad
selecteditem.
No olvidar el disenador.
Corrida:
1.- Observar que tenemos dos grupos de radiobotones uno con GRUPNAME=GRUPO1 y otro con
GROUPNAME=GRUPO2 sin embargo cada radiobuton tiene su propio valor o ID.
2.- La razon principal para esta situacion es que los radiobotones son mutuamente excluyentes entre si Y
QUE SOLO UNO PUEDE ESTAR ENCENDIDO A LA VEZ por eso los agrupamos con la propiedad GROUPNAME
para que html los pueda considerar como dos o mas grupos diferentes.
3.- Tambien pueden usar la propiedad checked=true para que aparezcan seleccionados al cargar el
programa .aspx
4.- Para programarlo usar la misma tecnica que se analizo con CHECKBOX es decir revisar la propiedad
checked y un monton de if's ( un if por cada radiobutton).
5.- DISENADOR POR FAVOR
Corrida:
Como se observa checkbox son cajitas con una palomita y radiobutton son circulitos con un puntito negro.
Pero su diferencia mas importante es que radiobtuton no permite que esten seleccionados dos o mas de
ellos a la vez (dentro del mismo grupo o groupname).
RADIOBUTTONLIST:
Programa:
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
Protected Sub EVENTO1(ByVal sender As Object, ByVal e As System.EventArgs)
' como es un control similar a listbox, tambien puede usar prop selecteditem
Label1.Text = SEXO.SelectedItem.Text
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>PROGRAMACION VISUAL BASIC ASPX</title>
</head>
<body>
<form id="form1" runat="server">
SEXO:<BR>
<ASP:RADIOBUTTONLIST ID=SEXO RUNAT=SERVER>
<ASP:LISTITEM TEXT=MASCULINO />
<ASP:LISTITEM TEXT=FEMENINO />
</ASP:RADIOBUTTONLIST>
<ASP:BUTTON ID="BUTTON1" ONCLICK=EVENTO1 TEXT=OK RUNAT=SERVER /><BR>
<ASP:LABEL ID=Label1 RUNAT=SERVER /><BR>
</form>
</body>
</html>
Nota:
Se esta usando un objeto listbox para procesar el conjunto de datos recordar que listbox, dropdownlist,
comboboxlist, etc son objetos similares y por tanto se pueden usar para estos problemas.
Se esta usando la propiedad add de la coleccion items del componente o control listbox (lista).
Observar que para encadenar strings en Visual Basic se usa el signo &
Y el metodo items.clear() es porque cuando el usuario usa el click mas de una vez el control listbox los
agrega abajo por eso en cuanto se activa el onclick lo primero que se realiza es limpiar el listbox.
El Disenador no olvidar usarlo.
Corrida:
Corrida
While puede llevar dos condiciones en este caso inicializar 2 variables de condicion y cuidar que existan 2 de
rompimiento o terminacion de ciclo.
El grupo cierto de instrucciones puede ser una sola instruccion o todo un grupo de instrucciones.
La condicion puede ser simple o compuesta.
A este ciclo tambien se le conoce tambien como ciclo de condicion de entrada o prueba por arriba porque
este ciclo evalua primero la condicion y posteriormente ejecuta las instrucciones.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- DESPLEGAR ENTEROS ENTRE 50 Y 80
2.- DESPLEGAR MULTIPLOS DE 4 ENTRE 60 Y 20 ACOMPANADOS DE SU LOGARITMOS DE BASE 10 Y BASE
e RESPECTIVOS ( revisar tema operadores atitmeticos)
3.- CONSTRUIR LA TABLA DE DIVIDIR QUE EL USUARIO INDIQUE.
4.- Evaluar una funcion cualesquiera para el rango de valores de x de -3 a +5
Corrida:
Otra diferencia basica con el ciclo do while loop es que aunque la condicion sea falsa desde un principio el
cuerpo de instrucciones se ejecutara por lo menos una vez.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- tres tareas del for
2.- dos tareas del while
30
40
SUC B 50 60
70
80
type.
LastIndexOf Overloaded. Returns the index of the last occurrence of a value in a one-dimensional Array or
in a portion of the Array.
Reverse Overloaded. Reverses the order of the elements in a one-dimensional Array or in a portion of the
Array.
SetValue Overloaded. Sets the specified element in the current Array to the specified value.
Sort Overloaded. Sorts the elements in one-dimensional Array objects.
ToString (inherited from Object) Returns a String that represents the current Object.
FUENTE: Ayuda Microsoft Net
Notas:
En visual Basic 2005 recordar que la primera posicion o renglon en una lista es la posicion o renglon 0
(cero).
El dato capturado, proviene de momento de un componente escalar textbox y/o se usan tantos de estos
controles como elementos tenga el arreglo o mas facil aun se debera controlar la captura de elementos
usando algun algoritmo sencillo de validacion como lo muestra el programa ejemplo.
Programa
<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
' DECLARANDO LISTA GLOBAL FUERA DEL SUB
Shared EDAD(4) As Integer
' DECLARANDO RENG COMO GLOBAL
Shared REN As Integer
Protected Sub CARGAR(ByVal sender As Object, ByVal e As System.EventArgs)
If REN <= 4 Then
EDAD(REN) = EDAD1.Text
REN = REN + 1
EDAD1.Text = " "
End If
' no olvidar poner el textbox EDAD en la forma
If REN = 5 Then EDAD1.Visible = False
End Sub
Protected Sub PROCESO(ByVal sender As Object, ByVal e As System.EventArgs)
' LIMPIANDO LISTAS
LISTA1.Items.Clear()
LISTA2.Items.Clear()
'CARGANDO LISTA EDAD CAPTURADA
For REN = 0 To 4
LISTA1.Items.Add(EDAD(REN))
Next
' OPERACIONES
For REN = 0 To 4
EDAD(REN) = EDAD(REN) * 12
Next
' DESPLEGANDO
For REN = 0 To 4
LISTA2.Items.Add(EDAD(REN))
Next
Corrida:
Notas:
En la forma deben poner un textbox EDAD.
Observar que en el programa el arreglo edad y la variable renglon se declararon de tipo SHARED porque los
dos metodos el de captura y el de operacion despliegue las estan compartiendo.
Para el caso de operaciones y comparaciones con todos los elementos de la lista a la vez se debera usar un
ciclo for con una variable entera llamada renglon, misma que tambien se usa como indice de la lista.
Recordar que todos los datos internos de la lista estaran almacenados en la memoria ram del computador,
para despliegues se usa un componente visual que permite manipular un conjunto de datos a la vez, el
ListBox con sus metodos apropiados pero se tiene que usar un ciclo for() para ir anadiendo o agregando
elemento por elemento como se observa en el problema ejemplo que se ha venido desarrollando, en este
caso se quiere desplegar las cinco edades convertidas a meses.
Notas:
Observar el formato de declaracion y como se controlan los indices de captura r, c.
Para procesar los elementos se usan dos ciclos for y el formato tabla (reng, col).
Recordar que un programa en visual web developer 2005 es un conjunto de objetos de diferente fuente
interactuando entre si en este problema se uso el objeto LISTBOX para preesentar el resultado mas
adelante se usara un objeto mas apropiado.
Corrida:
Recordar que el primer indice en un ListBox es el cero por eso el ciclo va desde el cero hasta la cantidad de
elementos menos uno.
Corrida:
COMO ULTIMA NOTA IMPORTANTE ES QUE EXISTEN OTROS DOS CONTROLES QUE PUEDEN
COMPORTARSE Y USAR LOS MISMOS METODOS ASOCIADOS A LISTBOX, ESTOS CONTROLES SON
EL COMBOBOX Y DATALIST( EN PROXIMOS CURSOS SE INCLUIRAN COMO DOS TEMAS EXTRAS)
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- CAPTURAR EN UNA LISTA LOS SUELDOS DE 6 EMPLEADOS Y DESPLEGARLOS EN UNA SEGUNDA LISTA
AUMENTADOS EN UN 30%
2.- CAPTURAR EN UNA LISTA LOS PESOS EN KILOGRAMOS DE 6 PERSONAS DESPLEGARLOS EN UNA
SEGUNDA LISTA CONVERTIDOS A LIBRAS Y ADEMAS SOLO LOS MAYORES DE 100 LIBRAS.
3.- CAPTURAR EN SUS 4 LISTAS RESPECTIVAS MATRICULA, NOMBRE Y DOS CALIFICACIONES DE 5
ALUMNOS, DESPUES CALCULAR UNA LISTA DE PROMEDIOS DE CALIFICACIONES.
4.- CAPTURAR EN SUS LISTAS RESPECTIVAS NUMEMPLEADO, NOMEMPLEADO, DIAS TRABAJADOS Y
SUELDO DIARIO DE 5 EMPLEADOS, DESPLEGAR EN OTRA PANTALLA O PANEL LA NOMINA PERO SOLO DE
AQUELLOS EMPLEADOS QUE GANAN MAS DE $300.00 A LA SEMANA.
Suc A 1
Suc B 5
Suc C 9
10
11
12
Recordar que son los datos numericos internos quienes se procesan (es decir, se capturan, se realizan
operaciones con ellos, se despliegan, etc.) es la informacion externa quien le da sentido.
Es importante tambien entender que un objeto TABLE es una coleccion o conjunto de objetos de
tipo TABLEROW (y por ser objetos cada renglon tambien debera ser creado usando el operador
new) ademas de que cada celda en cada uno de los renglones tambien sonun objeto de tipo
TABLECELL (es decir cada celda tambien debera ser creada usando new).
Algunas de sus propiedades y metodos mas interesantes que se usan en el programa ejemplo son:
CellPadding.- Se usa para definir el tamano del marco o separador de la celdas
GridLine.- Se usa para indicar si el marco debera ser solo vertical, horizontal o ambos.
Text.- Propiedad de la celda(TABLECELL) que se usa para manipular y procesar el dato.
Add.- Otra propiedad de CELL y tambien de ROW que se puede usar para cargar un dato en una celda o una
celda en un renglon.
Como se observa de las dos propiedades anteriores CELDA es el elemento mas importante de una TABLA,
CELDA tiene muchas propiedades y metodos y en el caso particular de TEXT y ADD recordar que TEXT tiene
las caracteristicas de get-set que ya se ha analizado en temas anteriores y por tanto sera mas util o usado
Se empieza creando un objeto de tipo pagina (PAGE) de html la razon de esto es doble primero porque se
necesita crear y tambien inicializar un objeto table y se aprovecha el metodo ONLOAD DE PAGE para
realizar este proceso es decir en cuanto se carga la pagina se inicializa la tabla.
En cuanto a la creacion e inicializacion de la tabla recordar que TABLEROW y TABLECELL son objetos y por
tanto se uso el operador new.
Recordar tambien que cuando se crean o inicializan tablas se usan CANTRENG y CANTCOL, sin embargo
cuando se va a acceder o manipular las celdas mas adelente en el programa se debera usar notacion
[0][0].
Observar que Celda usa el metodo set en CELDA.TEXT=DATO
Para cargar la celda al renglon respectivo asi como para cargar el renglon a la tabla (otro objeto tambien)
se usa el metodo ADD.
Ya dentro del metodo de CARGAR observar que para procesar una celda determiNADA se debera usar toda
la ruta completa es decir TABLA.RENGLON.CELDA; en el caso de renglon y columna o celda respectiva
usando su [indice] correspondiente.
Como se esta cargando TEXT de TextBox a TEXT de CELL, solo se igualaron las propiedades respectivas.
El resto de codigo en CARGAR ya se analizo en tema anterior solo es para validar no salir de los limites de
la tabla avisar cuando ya se lleno O PONER VISIBLE EN FALSE y dejarla lista para una nueva captura se
usan los dos textboxs como indices de reng y col respectiva.
En el metodo PROCESO, se usan los ciclos normales de for (renglon) y for(columna), los indices empiezan
en 0, y el metodo TEXT de CELL con todas las notas vistas en temas anteriores.
Corrida:
Un proceso muy comun con tablas, cuadros y concentrados es agregarles listas de totales y promedios ya
sea por columna o por renglon, o ambas por ejemplo:
CIA ACME
INGRESOS MENSUALES
(MILES DE PESOS)
ene
Suc a
Suc b
15
Suc c
24
Suc d
10 11
12
33
11
totmes 22 26
30
Observar que se puede crear el procedimiento o los procedimientos arriba o abajo de la parte principal del
programa.
Corrida:
Observar que en el procedimiento los parametros crean variables de manera local es decir variables que
solo pueden usar dentro del procedimiento estas variables son quienes reciben los datos o valores.
REGLAS PARA EL USO DE PARAMETROS:
1.- Cuando se usan variables como parametros la variable que se manda debe ser declarada dentro del
principal o del procedimiento de donde se esta enviando.
2.- La variable que se manda tiene un nombre, la que se recibe puede tener otro nombre o el mismo
nombre por claridad de programa, pero recordar que internamente en la memoria del computador existiran
dos variables diferentes.
3.- La cantidad de variables que se envian deben ser igual en cantidad, orden y tipo a las variables que
reciben.
4.- La variable que se recibe tiene un ambito local dentro del procedimiento, es decir solo la puede usar ese
procedimiento.
5.- Se puede mandar a un procedimiento un dato una variable(como lo muestran los ejemplos) o una
expresion algebraica (no ecuacion o formula) pero siempre se deberan recibir en una variable.
Corrida:
Corrida:
Corrida:
Es permitido poner mas de un return en el cuerpo de instrucciones sobre todo en condiciones pero solo un
return se ejecutara ejemplo;
if (suma >= 10)
{ return 10; }
else
{ return 20; }
EXISTEN 3 CLASES USUALES DE FUNCIONES EN VISUAL WEB DEVELOPER 2005 Visual Basic .
Las primeras son de tipo computacional que son disenadas para realizar operaciones con los argumentos y
regresan un valor basado en el resultado de esa operacion.
Las segundas funciones son aquellas que manipulan informacion y regresan un valor que indican la
terminacion o la falla de esa manipulacion.
Las terceras son aquellas que no regresan ningun valor, es decir son estrictamenta procedurales.
Esto quiere decir que en general toda operacion o calculo en un programa debera convertirse a una
o muchas funciones, y el resto deberan ser procedimientos.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Capturar 3 calificaciones y nombre en principal(EVENTO1) calcular promedio en una funcion, desplegar
en principal.
2.- Crear una tabla de multiplicar, captura y control de ciclo en el principal, operaciones en una funcion,
despliegue en el principal. (cs)
Corrida:
Es de recordar que los cambios que le hagan al arreglo dentro de la funcion se reflejaran en el arreglo
original, es por esto que si se quiere modificar un arreglo en una funcion no hay necesidad de regresar
ningun valor.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Inicializar 10 edades en el principal mandar la lista a un procedimiento que la convierte a meses,
desplegar en principal.
2.- Capturar un arreglo de 7 ciudades en un primer procedimiento, sortear en un segundo y desplegar en
un tercero, la lista original y la lista ordenada.
ESTILO
MEDIDA
COLOR
MATERIAL
JEANS
SPORT
GRANDE
AZUL
ALGODON
VOLIS
VESTIR
MEDIANA NEGRA
POLIESTER
MORADO RARON
Tabla: Clientes
NUMCLIENTE NOMCLIENTE
DIRCLIENTE
TELCLIENTE
JUAN PEREZ
AV ABA 2233
2345678
ROSA MARES
Recordar siempre una tabla almacena o representa un conjunto de datos del mismo tipo o entidad, la tabla
de alumnos es para almacenar y manipular muchos alumnos, la tabla de productos es para almacenar y
manipular muchos alumnos, en resumen si en un problema de informacion solo se presenta una instancia o
renglon de una entidad logica, entonces no es tabla, es un encabezado.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.-CONSTRUIR EN CUADERNO LAS SIGUIENTES TABLAS, LA MITAD DE ELLAS CON EL PRIMER FORMATO Y
LA SEGUNDA MITAD CON EL SEGUNDO FORMATO.
1.- PACIENTES
2.- PERROS
3.- PLUMAS
4.- MERCANCIAS
5.- PELICULAS
6.- MEDICINAS
7.- MAESTROS
8.- AUTOS
9.- COMPUTADORAS
10.- BANCOS
Fuente microsoft.net
Como ven esta bastante claro y no ocupa explicacion,
Empezando:
El problema es comunicar un programa o aplicacion aspx con una base de datos y mas que comunicar se
pretende que el programa o aplicacion realize una serie de procesos u operaciones con la base de datos o
mejor aun con el conjunto de tablas que contiene una base de datos.
La primera nota a recordar es que una base de datos puede estar fisicamente en el servidor o en algun
folder o directorio del disco duro de dicha maquina servidora.
Sin embargo tambien es necesario conocer que asi como existen servidores de paginas(web server),
servidores de correo (mail server), servidores de ftp (ftp server), etc, tambien existen servidores de bases
de datos (database server), los mas comunes son el sqlserver de microsoft, oracle, mysql, etc, estos
servidores tambien pueden crear, administrar y procesar una base de datos, por supuesto que el
procedimiento que se dio para crearla en access en el tema anterior no se puede usar para crear y cargar
una base de datos en un servidor de bases de datos.(esperar libros de bases de datos en programacionfacil
en un proximo futuro).
El modo de comunicarse entre nuestro programa o aplicacion aspx y la base de datos (ya sea fisica o un
dbserver), implica que ambos manejen un lenguaje de programacion comun, es decir no se puede mandar
una instruccion en csharp, o en basic o pascal a la base de datos y ademas esperar que esta ultima la
entienda (para entender esto, una razon muy sencilla es que la base de datos tendria que conocer o
comprender todos los lenguajes de programacion), para resolver este problema de comunicacion es que se
usa un lenguaje comun de bases de datos que tanto los lenguajes de programacion existentes como las
bases de datos entienden, este lenguaje comun de bases de datos es el SQL (structured query languaje) o
lenguaje estructurado de consultas.
En otras palabras, ustedes mis estimados lectores tendran que aprender este nuevo lenguaje de
programacion el SQL, la buena noticia es que es un lenguaje con muy pocas instrucciones y
ademas existen muy buenos tutoriales en internet que hay que buscar y estudiar.
PROPAGANDA, ya ven que en este curso estan aprendiendo el lenguaje de programacion VISUAL
Visual Basic, el lenguaje de programacion HTML y ahora el lenguaje de programacion SQL, !wow!
tres lenguajes por el precio de uno.
Bueno las principales instrucciones de SQL que se usan en este curso son SELECT, INSERT, UPDATE y
DELETE.
La pregunta es ahora como mandamos las instrucciones sql a la base de datos, la respuesta son los
OBJETOS ADO.NET que estamos analizando en orden y proposito de uso, los estaremos explicando.
OBJETO CONNECTION:- OBJETO QUE SE UTILIZA PARA ESTABLECER UNA CONECCION O ENLACE A LA
BASE DE DATOS.
Este objeto primero se tendra que crear en el programa y luego se tendra que cargar con dos parametros
(ver ejemplo mas abajo), el primer parametro es el provedor o la fuente que proporcionara los datos, los
provedores o fuentes de datos que existen son:
SQLSERVER NET DATA PROVIDER.- QUE SE ESPECIALIZA EN COMUNICARSE Y PROCESAR BASES DE DATOS
CONSTRUIDAS CON MICROSOF SQL SERVER V7.0 Y ES EL QUE SE USA EN ESTE CURSO
OLEDB.NET DATA PROVIDER.- QUE SE ESPECIALIZA EN COMUNICARSE Y PROCESAR BASES DE
DATOS QUE A LA FECHA DEL PRESENTE LIBRO UTILIZEN ALGUNOS DE LOS SIGUIENTES DRIVERS,
SQLOLEDB ( VERSIONES ANTERIORES DE SQL SERVER DE MICROSOFT), MSDAORA (ORACLE),
MICROSOFT.JET ( ACCESS Y ALGUNOS OTROS DBMS DE MICROSOFT)
ODBC.NET .- BASES DE DATOS QUE USAN ODBC COMO MEDIO DE COMUNICACION CON OTRAS BASES DE
DATOS Y APLICACIONES COMO NOTA A CONSIDERAR ODBC.NET NO ESTA INCLUIDA POR DEFAULT EN
MICROSOFT.NET, SE TIENE QUE BAJAR DE MICROSOFT.
El segundo parametro es la propia base de datos con la cual se comunicara el programa o aplicacion.
Ejemplo del objeto CONNECTION
Static OleDbConnection coneccion;
coneccion = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=c:\\progfacil\\tusitio\\mibase.mdb");
Es una sola string y los dos parametros mencionados van separados por el punto y coma.
ATENCION es DATA SOURCE= no usar DATASOURCE= estan adevertidos.
ejemplos de los otros poveedores o fuentes mencionados:
//Provider=MSDAORA; Data Source=ORACLE8i7; User ID=OLEDB; Password=OLEDB
//Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\bin\LocalAccess40.mdb;
//Provider=SQLOLEDB;Data Source=MySQLServer;Integrated Security=SSPI;
OBJETO COMMAND.Ya establecido el canal o enlace entre el programa aspx y la base de datos via el objeto CONECCION, se
debe mandar la instruccion SQL a la propia base de datos, sin embargo en un programa de csharp por
supuesto que no puede contener instrucciones de otros lenguajes de programacion como el de SQL, es por
esto que se deberan usar algunos de los otros objetos de ADO.NET para que estos objetos transporten la
instruccion sql hacia la base de datos (y transporte de regreso al servidor los datos de alguna tabla) uno de
estos objetos es el objeto COMMAND.
Este objeto puede contener directamente una instruccion SQL y enviarla al objeto coneccion ya descrito.
En particular se usara COMMAND principalmente para que transporte las instrucciones SQL insert,
update y delete Y DE VEZ EN CUANDO SELECT.
Este objeto puede contener directamente una instruccion SQL y enviarla al objeto coneccion ya descrito.
Este objeto command primero se tendra que crear y luego cargarle dos parametros que son:
la instruccion sql y el objeto conneccion que ya se vio en el parrafo anterior. Ejemplo
OleDbCommand orden;
orden= new OleDbCommand("select * from mitabla", coneccion);
Si esta muy grande o muy compleja la instruccion sql, es mas conveniente crearla en una variable string y
poner la variable como parametro ejemplo:
OleDbCommand orden;
String q="select * from mitabla";
orden= new OleDbCommand(q, coneccion);
Sin embargo ciertas instrucciones de sql (ya estudiaron su tutorial del sql?) requieren que se
manden los datos a la base de datos, respetando el tipo de dato con los cuales los creo el
software de bases de datos, por ejemplo si edad en access se declaro como NUMBER, la instruccion
sql que prentenda cargar dicho campo, tiene la obligacion de mandarla con este tipo de dato
asociado, instrucciones SQL que permiten cargar o capturar ese campo edad son INSERT o UPADTE (ya
estudiaron su tutorial de SQL??).
Para resolver este problema, usaremos en la **string q**, unas variables especiales llamadas
**VARIABLES PARAMETROS** que se simbolizan usando el simbolo @ antes de la variable y ademas al
objeto COMMAND le agregamos dos instrucciones extras que permiten agregar a la string q el dato y
el tipo de dato, ejemplo, se tienen seis renglones ya capturados en nuestra tabla y se quiere
agregar un septimo renglon con los siguientes datos, clave=7, nombre="rana" peso=3.14 usaremos una
instruccion SQL INSERT ej:
OleDbCommand orden;
String clave=7;string nombre="rana"; string peso=3.14;
string q="insert into mitabla(clave,nombre,peso) values(@CLAVE, @NOMBRE, @PESO)";
orden= new OleDbCommand(q, coneccion);
orden.Parameters.Add(new OleDbParameter("@CLAVE", OleDbType.Integer));
orden.Parameters["@CLAVE"].Value = clave;
orden.Parameters.Add(new OleDbParameter("@NOMBRE", OleDbType.VarWChar, 40));
orden.Parameters["@NOMBRE"].Value = nombre;
orden.Parameters.Add(new OleDbParameter("@PESO", OleDbType.Double));
orden.Parameters["@PESO"].Value = edad;
Observar que para cada variable parametro, se tienen que cargar dos elementos, el valor y el tipo de
dato correpondiente.
Aunque en valor se manda string's en oledbtype se hace un mapeo, relacion o conversion al tipo de dato
que se uso en access, tener mucho cuidado que exista una relacion igual o cuando este pograma se ejecute
el servidor les va a mandar un error o excepcion de sql que les intenta decir que el tipo de dato que
mandaron a la base de datos, no es igual al que se uso para crearlo en la base de datos.
Los OLEDBTYPE mas comunes son:
BigInt A 64-bit signed integer (DBTYPE_I8). This maps to Int64.
Binary A stream of binary data (DBTYPE_BYTES). This maps to an Array of type Byte.
Boolean A Boolean value (DBTYPE_BOOL). This maps to Boolean.
BSTR A null-terminated character string of Unicode characters (DBTYPE_BSTR). This maps to String.
Char A character string (DBTYPE_STR). This maps to String.
Currency A currency value ranging from -2 63 (or -922,337,203,685,477.5808) to 2 63 -1 (or
+922,337,203,685,477.5807) with an accuracy to a ten-thousandth of a currency unit (DBTYPE_CY). This
maps to Decimal.
Date Date data, stored as a double (DBTYPE_DATE). The whole portion is the number of days since
December 30, 1899, while the fractional portion is a fraction of a day. This maps to DateTime.
DBDate Date data in the format yyyymmdd (DBTYPE_DBDATE). This maps to DateTime.
DBTime Time data in the format hhmmss (DBTYPE_DBTIME). This maps to TimeSpan.
DBTimeStamp Data and time data in the format yyyymmddhhmmss (DBTYPE_DBTIMESTAMP). This maps
to DateTime.
Decimal A fixed precision and scale numeric value between -10 38 -1 and 10 38 -1 (DBTYPE_DECIMAL). This
maps to Decimal.
Double A floating point number within the range of -1.79E +308 through 1.79E +308 (DBTYPE_R8). This
maps to Double.
Empty No value (DBTYPE_EMPTY). This maps to Empty.
Error A 32-bit error code (DBTYPE_ERROR). This maps to Exception.
Filetime A 64-bit unsigned integer representing the number of 100-nanosecond intervals since January 1,
1601 (DBTYPE_FILETIME). This maps to DateTime.
Guid A globally unique identifier (or GUID) (DBTYPE_GUID). This maps to Guid.
IDispatch A pointer to an IDispatch interface (DBTYPE_IDISPATCH). This maps to Object. Note This data
type is not currently supported by ADO.NET. Usage may cause unpredictable results.
Integer A 32-bit signed integer (DBTYPE_I4). This maps to Int32.
IUnknown A pointer to an IUnknown interface (DBTYPE_UNKNOWN). This maps to Object. Note This data
type is not currently supported by ADO.NET. Usage may cause unpredictable results.
LongVarBinary A long binary value (OleDbParameter only). This maps to an Array of type Byte.
LongVarChar A long string value (OleDbParameter only). This maps to String.
LongVarWChar A long null-terminated Unicode string value (OleDbParameter only). This maps to String.
Numeric An exact numeric value with a fixed precision and scale (DBTYPE_NUMERIC). This maps to
Decimal. PropVariant An automation PROPVARIANT (DBTYPE_PROP_VARIANT). This maps to Object.
Single A floating point number within the range of -3.40E +38 through 3.40E +38 (DBTYPE_R4). This maps
to Single.
SmallInt A 16-bit signed integer (DBTYPE_I2). This maps to Int16.
TinyInt A 8-bit signed integer (DBTYPE_I1). This maps to SByte.
UnsignedBigInt A 64-bit unsigned integer (DBTYPE_UI8). This maps to UInt64.
UnsignedInt A 32-bit unsigned integer (DBTYPE_UI4). This maps to UInt32.
UnsignedSmallInt A 16-bit unsigned integer (DBTYPE_UI2). This maps to UInt16.
UnsignedTinyInt A 8-bit unsigned integer (DBTYPE_UI1). This maps to Byte.
VarBinary A variable-length stream of binary data (OleDbParameter only). This maps to an Array of type
Byte. VarChar A variable-length stream of non-Unicode characters (OleDbParameter only). This maps to
String.
Variant A special data type that can contain numeric, string, binary, or date data, as well as the special
values Empty and Null (DBTYPE_VARIANT). This type is assumed if no other is specified. This maps to
Object.
VarNumeric A variable-length numeric value (OleDbParameter only). This maps to Decimal.
VarWChar A variable-length, null-terminated stream of Unicode characters (OleDbParameter only). This
maps to String.
WChar A null-terminated stream of Unicode characters (DBTYPE_WSTR). This maps to String.
Fuente: microsoft net
Aun mas, con el ejemplo anterior el objeto COMMAND esta construido y preparado y cargado pero todavia
no se manda desde el programa a la base de datos, es decir le faltan activar las siguientes tres
propiedades, ejemplo;
OleDbCommand orden;
String clave=7;string nombre="rana";string peso=3.14;
string q="insert into mitabla(clave,nombre,peso) values(@CLAVE, @NOMBRE, @PESO)";
orden= new OleDbCommand(q, coneccion);
orden.Parameters.Add(new OleDbParameter("@CLAVE", OleDbType.Integer));
orden.Parameters["@CLAVE"].Value = clave;
Como se observa en este ejemplo muy sencillo, el dataadapter (orden) esta funcionando de manera muy
similar al primer ejemplo que se vio del objeto COMMAND pero tengan la seguridad que tambien se pueden
usar variables parametros y agregarles los dos tipos de parametros a este objeto dataadpater.
Observar que su propiedad FILL carga el DATASET (tabla) con una de las tablas en disco, recordar que en la
base de datos puede contener muchas tablas.
Ademas esa propiedad FILL es equivalente a las tres ultimas instrucciones del objeto COMMAND, es decir
open, executenonquery y close, mas facil verdad.
DATAREADER y DATASET:
Observar que tambien se usan en forma conjunta, primero es muy similar en uso y funcion que el objeto
DATAADAPATER, la diferencia entre datareader y dataadapter es el tipo de base de datos con las cuales se
pueden comunicar, dataadpater se especializan en bases de datos relacionales y datareader se especializa
en archivos, que no se estudian en este curso.
Tambien es importante mencionar que datareader es el objeto de ADO NET mas parecido al objeto
RESULTSET que uso mucho en el ADO anterior de microsoft.
TOMAR EN CUENTA QUE ESTE CURSO ESTA CONSTRUIDO ALREDEDOR DE MS SQL SERVER 2000 Y
HAY CAMBIOS EN CUANTO A LOS EJEMPLOS ARRIBA CITADOS, BASICAMENTE SE ESTARA USANDO
SQLCLIENT MUY SIMILAR A OLEDB.
EN general se han visto de manera sencilla los principales objetos ADO ASP (connection, command,
datareader, dataadapter, dataset), sin embargo la tabla o las tablas o la base de datos que se tiene en
disco o sirviendola algun servidor de bases de datos, se ha quedado en la memoria de la maquina del
cliente, ADONET ha terminado su trabajo y su funcion.
Para mandar el dataset a el browser se tendra que pasar a algun tipo de objeto visible que soporte el
browser, los objetos que se pueden usar para mandar el dataset a pantalla son:
1.- COMPONENTE TABLE DE HTML (USADO EN EL CURSO DE C SHARP CGI DE PROGRAMACIONFACIL.COM)
2.- COMPONENTE HTMLTABLE DE ASP
3.- COMPONENTE GRIDVIEW DE ASP NET 2.0 BETA y que se usa en este curso.
Observar que la primera string de coneccion es para ASP que es el primer y mas viejo modelo de enlace
con base de datos que realizo Microsoft.
Es la segunda string de ADO NET que se usara en este curso solo copy y paste a nuestro programa en la
parte correspondiente, tal como se muestra en el siguiente programa ejemplo.
Nuestro primer programa creara una tabla llamada tabla1 que contendra clave, nombre, edad y estatura de
algunos animalitos, tambien se le cargan algunos renglones de prueba.
Programa:
<%@ Page Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' creando y cargando objetos
Dim CANAL As SqlConnection
Dim ORDEN As SqlCommand
NOTAS:
1.- Observar que arriba en la parte de los imports del programa se TIENEN QUE AGREGAR KIS SUGUIENTES
IMPORTS:
<%@ Import Namespace=System %>
<%@ Import Namespace=System.Data %>
<%@ Import Namespace=System.Data.SqlClient %>
No olvider a agregar estos imports a tus programas, Data.SqlClient contiene todos los objetos ADO NET
(connection, command, etc) que se ocupan y manejan en el programa.
2.- Creamos primero el objeto sqlconnection llamado CANAL y se debe cargar con la string de connecion
que copiaron de hostbasket, esta string de coneccion contiene el servidor de ms sql server que estamos
accesando e informacion que ocupa dicho servidor tal como login password etc.
3.- Observar que todas las instrucciones que se estan enviando a la base de datos contienen una string q
que contiene la instruccion sql ( ya estudiaron su tutorial de sql) y un objeto SqlCommand llamado
ORDEN que transporta la instruccion sql a la base de datos.
Recordar que SQLCOMMAND se usara para enviar todas las instrucciones sql y en casos excepcionales
SELECT.
Recordar tambien como se indico en el tema pasado SQLCOMMAND puede llevar variables parametros que
no se esta usando en este programa ejemplo y ademas debe abrir coneccion (open) executar instruccion
(executenonquery) y cerrar (close) la coneccion o enlaze.
4.- La primera instruccion SQL que se usa es USE BASEDATOS, en este programa ejemplo es USE
MASTER, como ya se indico la base de datos gratis que nos proporciona hostbasket se llama MASTER y
primero se le esta indicando al servidor que estamos trabajando con esta base de datos (USE MASTER).
5.- La siguiente instruccion SQL es CREATE TABLE ( ya estudiaron su tutorial de sql ??) los tipos de datos
que pueden usar son:
Bigint Integer (whole number) data from -2^63 (-9,223,372,036,854,775,808) through 2^63-1
(9,223,372,036,854,775,807).
Int Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
Smallint Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767).
Tinyint Integer data from 0 through 255.
bit Integer data with either a 1 or 0 value.
decimal Fixed precision and scale numeric data from -10^38 +1 through 10^38 –1.
Numeric Functionally equivalent to decimal.
money Monetary data values from -2^63 (-922,337,203,685,477.5808) through
(+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit.
2^63
- 1
Smallmoney Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a tenthousandth of a monetary unit.
Float Floating precision number data with the following valid values: -1.79E + 308 through -2.23E - 308, 0
and 2.23E + 308 through 1.79E + 308.
Real Floating precision number data with the following valid values: -3.40E + 38 through -1.18E - 38, 0
and 1.18E - 38 through 3.40E + 38.
datetime Date and time data from January 1, 1753, through December 31, 9999, with an accuracy of
three-hundredths of a second, or 3.33 milliseconds.
smalldatetimeDate and time data from January 1, 1900, through June 6, 2079, with an accuracy of one
minute.
Char Fixed-length non-Unicode character data with a maximum length of 8,000 characters.
Varchar Variable-length non-Unicode data with a maximum of 8,000 characters.
Text Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters.
Nchar Fixed-length Unicode data with a maximum length of 4,000 characters.
Nvarchar Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a systemsupplied user-defined data type that is functionally equivalent to nvarchar(128) and is used to reference
database object names.
Ntext Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.
Binary Fixed-length binary data with a maximum length of 8,000 bytes.
Varbinary Variable-length binary data with a maximum length of 8,000 bytes.
Image Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.
Cursor A reference to a cursor.
sql_variant A data type that stores values of various SQL Server-supported data types, except text, ntext,
timestamp, and sql_variant.
Table A special data type used to store a result set for later processing .
Timestamp A database-wide unique number that gets updated every time a row gets updated.
Uniqueidentifier A globally unique identifier (GUID).
5.- (continuacion) Create TABLE incluye PRIMARY KEY, como ya se indico en el tema de tablas, cada
tabla debe llevar una identificador unico o campo o llave primaria, ademas create table lleva
IDENTITY(1,1) esta instruccion es para que el campo clave sea asignado automaticamente por el servidor
de MS SQL SERVER 2000 y la primera clave empieze en el numero 1 (uno) y las siguientes las vaya
incrementado de uno en uno , es decir IDENTITY(38,50) el primer campo clave sera el 38 y el siguiente
sera el 88.
6.- La ultima instruccion sql a usar es INSERT que se utiliza para cargar un renglo de la tabla con
informacion y como se estan cargando tres renglones de la tabla se estan usando tres INSERT's.
Corrida:
8.- Para ver si realmente la tabla esta creada y cargada con la informacion apropiada, pasamos al siguiente
tema de la unidad pero antes:
TAREAS PROGRAMACION WEB DEVELOPER 2005 Visual Basic
1.- Crear y cargar dentro dela base de datos MASTER tres de las tablas que se disenaron en el tema de
tablas de esta unidad y por favor ponerles nombres apropiados a las tablas, no poner tabla2, tabla3, etc.
Corrida:
Notas:
1.- No olviden agregar los imports sqlclient en la parte de arriba de los programas.
2.- Observar y siempre incluir los namespaces indicados.
3.- El componente GRIDVIEW pasarlo por las propiedades del disenador para que le den la mejor
presentacion posible.
4.- Recordar que GRIDVIEw es un WEBCONTROL por tanto hay que crearlo e inicializarlo al principio del
programa, tambien recordar que GridView tiene muchas propiedades que le mejoran la interfase con que se
despliega y es en esta parte donde se cargan dichas propiedades.
5.- Se empieza creando las variables globales a ocupar y abriendo la coneccion a la base de datos, si se les
hace muy grande la string del provedor, pueden cargarla primero en una variable string y carguen la string
en el constructor de la coneccion, pero esto es opcional.
6.- Recordar que hay otros provedores de bases de datos para cuando se quieran accesar bases de datos
diferentes de ms sql server.
7.- Se crea el adapter y se carga el constructor con la instruccion sql y la coneccion, aqui es necesario
entender que existen varias maneras de hacer esto:
Cargar una string con el sql y crear y usar un objeto command directamente por ejemplo objeto
comand(tringsql); y luego todavia se tendria que ejecutar con executenonquery(que ejecuta una string que
no regresa datos por ejemplo insert o update para un adapater) o executereader(si en lugar de usar adapter
se usa un reader) o executescalar( metodo que regresa un solo dato de la base de datos)
Usar algunas de las funciones descritas del adapter por ejemplo adpatercommandselect(stringsql)
Pero lo mas sencillo fue usar el metodo que se puso en el programa, es decir crear el adapter y pasarle
directamente la instruccion sql.
8.- Luego se creo el dataset y se cargo con toda la base de datos en disco, entender esto bien, dataset
puede quedar cargado con todas las tablas que tenga la base de datos por eso se usa un FILL para pasar al
dataset solo una de las tablas(mitabla), esto da origen a dos notas:
8.1.- al programar mas adelante se ocupara explicitamente indicarle al compilador con cual tabla se va a
trabajar, es por esta razon que se veran instrucciones tales como tabla.tables[clientes].etc.etc. Aqui se
esta diciendo al compilador que del dataset (TABLA) se va a realizar una proceso con la tabla de clientes.
8.2.- Para procesar dos o mas tablas, entonces se tendra que usar mucho el formato que se vio en la nota
8.1
9.- Al final se carga el gridview, se pega(binding) al dataset y se cierra la base de datos.
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Desplegar una tabla que crearon en las tareas del tema anterior.
2.- Construir una pagina que despliegue dos de las tablas del tema anterior ( sugerencia o usan dos botones
o usan procedimientos o usan paginas enlazadas).
UNIDAD 5: VISUAL WEB DEVELOPER 2005 Visual Basic LAS BASES DE DATOS
TEMA 8: Visual Basic INSERCION REGISTROS SQL INSERT
Insertar o agregar registros o renglones nuevos a una tabla en disco, es un proceso sencillo que usa la
siguiente instruccion sql:
INSERT INTO TABLA (CAMPO1,CAMPO2..) VALUES(VALOR1,VALOR2..);
Recordar que solo se esta usando lo minimo de cada instruccion sql, es conveniente estudiar un tutorial de
sql.
Tambien recordar que INSERT, UPDATE y DELETE van dentro de un objeto COMMAND.
Programa
<%@ Page Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
' CONTADOR ES UNA VARIABLE GLOBAL
Dim cont As Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' creando y cargando objetos
Dim CANAL As SqlConnection
Dim ORDEN As SqlCommand
Dim q As String
' string de coneccion y enlazando
CANAL = New SqlConnection(" Persist Security Info=True;User ID=lsoto;Password=TUPASSWORD;Initial
Catalog=lsoto;Data Source=sql13.hostbasket.com")
'creando y cargando un objeto SQLCOMMAND
' instruccion sql a usar es insert into mitabla(listacampos) values(listadatos)
' @variable es una variable de tipo parametro
q = "insert into mitabla(nombre,edad,estatura) values(@NOMBRE, @EDAD, @ESTATURA)"
ORDEN = New SqlCommand(q, CANAL)
' cargando dos parametros por cada textbox
ORDEN.Parameters.Add(New SqlParameter("@NOMBRE", SqlDbType.NVarChar, 20))
ORDEN.Parameters("@NOMBRE").Value = NOMBRE.Text
ORDEN.Parameters.Add(New SqlParameter("@EDAD", SqlDbType.Int))
ORDEN.Parameters("@EDAD").Value = EDAD.Text
ORDEN.Parameters.Add(New SqlParameter("@ESTATURA", SqlDbType.Float))
ORDEN.Parameters("@ESTATURA").Value = ESTATURA.Text
' mandando sql a la base de datos
ORDEN.Connection.Open()
ORDEN.ExecuteNonQuery()
ORDEN.Connection.Close()
' limpiando TEXTBOXS para otra inserccion
NOMBRE.Text = " "
EDAD.Text = " "
ESTATURA.Text = " "
' avisando inserccion
cont = cont + 1
Label5.Text = "REGISTRO no: " + cont.ToString() + " Insertado"
End Sub
</script>
Corrida:
Notas:
Se agregaron tres textboxs arriba para capturar los nuevos datos a insertar en la tabla.
RECORDAR QUE CAMPO CLAVE ES DE TIPO IDENTITY Y MS SQL SERVER 2000 SE ENCARGA DE
INCREMENTARLO POR SU CUENTA.
En funcion INSERTAR (), se crea la string q con el formato apropiado sql (como se dijo al principio de este
tema), observar que existen tres variables que llevan un @ antes, estas variables se llaman VARIABLES
PARAMETROS, y se cargan con el objeto command.parameters()
Otra vez, en este ejemplo para mandar la instruccion sql a la base de datos se crea y se usa un objeto
command (llamado orden) que lleva como datos la string q y la coneccion, pero se deben agregar dos
metodos command.parameters (orden.parameters()) por cada textbox que se vaya a enviar a la
tabla de la base de datos , en estos metodos se cargan las variables parametro primero con el valor de
dato del textbox y luego se transforman al tipo de dato apropiado usando los sqldbtype (mismos que los
pueden obtener del disenador de paginas que estan usando mucho para construir los programas ?verdad? ).
Ya con el objeto COMMAND(orden) listo y cargado para comunicar la instruccion sql a la base de datos se
abre la coneccion a la base de datos se manda el executenonquery(no se quiere regresar en esta parte,
recordar la nota respectiva que se dio en un tema anterior) y se cierra la coneccion y si dios quiere ya se
mando el nuevo renglon a la base de datos en disco.
Para asegurarse que ya se efectuo la inserccion en la base de datos, se tendra que usar el programa de
consulta o despliegue (SELECT) de el tema anterior
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Construir muchos programas de inserccion en las tablas que tengan construidas
2.- Ir Preparando una pagina de MENU que contenga las opciones de consulta (select) e inserccion (INSERT)
para una tabla ( pueden ser procedimientos o paginas enlazadas).
nota: no hay nuevo es una combinacion de los dos programas anteriores con las mismas notas, solo se usa
un textbox para pedir la clave, aunque se puede usar cualquier campo para buscar.
Corrida:
Nota: Es el programa anterior pero con otra condicion WHERE pero seria prudente mejor usar dos
combobox uno para la variable otro para el operador relacional y un text para el dato y mandar estos tres
datos al programa (se ocupan varios command.parameters()) pero eso queda de tarea.
Corrida:
UNIDAD 5: VISUAL WEB DEVELOPER 2005 Visual Basic LAS BASES DE DATOS
TEMA 12: PROGRAMACION VISUAL Visual Basic BAJAS O ELIMINACION SQL DELETE
Eliminacion es otro proceso simple y comun con las bases de datos el modelo con ADO NET que estamos
usando hace este tipo de operaciones muy faciles:
La instruccion sql a usar es:
DELETE FROM TABLA WHERE CONDICION
Y DELETE USA OBJETO COMMAND
Programa
<%@ Page Language="VB" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' creando y cargando objetos
Dim CANAL As SqlConnection
Dim ORDEN As SqlCommand
Dim q As String
' aqui es donde se usa la string de coneccion
CANAL = New SqlConnection(" Persist Security Info=True;User ID=lsoto;Password=TUPASSWORD;Initial
Catalog=lsoto;Data Source=sql13.hostbasket.com")
' creando COMMAND recordar que UPDATE --> usara command
q = "delete from mitabla where clave=@CLAVE"
ORDEN = New SqlCommand(q, CANAL)
ORDEN.Parameters.Add(New SqlParameter("@CLAVE", SqlDbType.SmallInt))
ORDEN.Parameters("@CLAVE").Value = CLAVE.Text
' Mandando la ORDEN
ORDEN.Connection.Open()
ORDEN.ExecuteNonQuery()
ORDEN.Connection.Close()
' Avisando
Label2.Text = "REGISTRO ELIMINADO"
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>BASES DE DATOS</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="CLAVE A ELIMINAR"></asp:Label> <asp:TextBox
ID="CLAVE" runat="server" Width="46px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="BAJA" /><br />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Label" Width="52px"></asp:Label>
</form>
</body>
Corrida:
Pantalla
Realmente este programa debe combinarse con el de busqueda por ejemplo en un panel buscar y desplegar
el registro y en otro panel este programa que hace la edicion.
Tambien se puede poner un boton que active el programa con la PAGINA de busqueda para que el usuario
vea el registro original y en un panel poner este codigo de edicion.
En ambos casos queda de tarea pero recordar que el menu que ya deben estar construyendo ya puede
activar la pagina.
Un registro editado o modificado, analizar con cuidado el codigo del programa, que esta documentado,
suerte
TAREAS PROGRAMACION VISUAL WEB DEVELOPER 2005 Visual Basic
1.- Construir el modulo o procedimeinto o pagina de edicion al sistema de menu que estan construyendo
Corrida:
PROYECTO PROGRAMACION VISUAL WEB DEVELOPER Visual Basic 2005 CONSTRUIR UN SISTEMA
COMPLETO INTEGRADO CON TODAS LAS OPERACIONES USANDO AL MENOS UNA TABLA EN MS SQL
SERVER 2000.
POR ULTIMO RECORDAR QUE EL COMPONENTE GRIDVIEW ASI COMO VARIOS MAS SON LOS CONTROLES
QUE MAS HA SIDO MODIFICADO Y ACTUALIZADO POR MICROSOFT, ENTRE SUS PRINCIPALES CAMBIOS ES
LA CANTIDAD INCREIBLE DE EVENTOS QUE PUEDE DETECTAR Y DE HECHO MUCHOS DE LOS PROCESOS
QUE SE ESTUDIARON EN ESTA UNIDAD SE PODRIAN FACILITAR MUCHO SI SE USARAN LOS EVENTOS DE
VIEWGRID, SIN EMBARGO POR RAZONES PEDAGOGICAS SE SELECCIONO EL MODELO SEGUIDO EN LA
UNIDAD, SIN EMBARGO EN LA PROXIMA ACTUALIZACION DE ESTE LIBRO SE ANALIZARAN Y ESTUDIARAN
TODOS ESTOS NUEVOS CONCEPTOS.
tan tan el curso se acabo y esten pendiente de los proximos de perl, visual basic 2005, javascript, php,
phyton, xml, et al
Command Object
The ADO Command object is used to execute a single query against a database. The query can perform
actions like creating, adding, retrieving, deleting or updating records.
If the query is used to retrieve data, the data will be returned as a RecordSet object. This means that
the retrieved data can be manipulated by properties, collections, methods, and events of the Recordset
object.
The major feature of the Command object is the ability to use stored queries and procedures with
parameters.
ProgID
set objCommand=Server.CreateObject(ADODB.command)
Properties
Property
Description
ActiveConnection
CommandText
CommandTimeout
CommandType
Name
Prepared
Sets or returns a Boolean value that, if set to True, indicates that the command
should save a prepared version of the query before the first execution
State
Command
object
is open, closed,
Methods
Method
Description
Cancel
Collections
Collection Description
Parameters Contains all the Parameter objects of a Command Object
Properties
Connection Object
The ADO Connection Object is used to create an open connection to a data source. Through this
connection, you can access and manipulate a database.
If you want to access a database multiple times, you should establish a connection using the Connection
object. You can also make a connection to a database by passing a connection string via a Command or
Recordset object. However, this type of connection is only good for one specific, single query.
ProgID
set objConnection=Server.CreateObject(ADODB.connection)
Properties
Property
Description
Attributes
CommandTimeout
ConnectionString
ConnectionTimeout Sets or returns the number of seconds to wait for a connection to open
CursorLocation
DefaultDatabase
IsolationLevel
Mode
Provider
State
Version
Methods
Method
Description
BeginTrans
Cancel
Cancels an execution
Close
Closes a connection
Open
Opens a connection
OpenSchema Returns schema information from the provider about the data source
RollbackTrans Cancels any changes in the current transaction and ends the transaction
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic, Visual C++, and Visual
J++ languages can handle events).
Event
Description
BeginTransComplete
Disconnect
ExecuteComplete
InfoMessage
WillExecute
Collections
Collection Description
Errors
Properties
Error Object
The ADO Error object contains details about data access errors that have been generated during a single
operation.
ADO generates one Error object for each error. Each Error object contains details of the specific error,
and are stored in the Errors collection. To access the errors, you must refer to a specific connection.
To loop through the Errors collection:
Syntax
objErr.property
Properties
Property
Description
Description
HelpContext Returns the context ID of a topic in the Microsoft Windows help system
HelpFile
Returns the full path of the help file in the Microsoft Windows help system
NativeError
Number
Source
Returns the name of the object or application that generated the error
SQLState
Field Object
The ADO Field object contains information about a column in a Recordset object. There is one Field
object for each column in the Recordset.
ProgID
set objField=Server.CreateObject(ADODB.field)
Properties
Property
Description
ActualSize
Attributes
DefinedSize
Name
NumericScale
object
OriginalValue
Precision
Sets or returns the maximum number of digits allowed when representing numeric
values in a Field object
Status
Type
Methods
Method
Description
Returns all or a part of the contents of a large text or binary data Field object
Collections
Collection Description
Properties
Parameter Object
The ADO Parameter object provides information about a single parameter used in a stored procedure or
query.
A Parameter object is added to the Parameters Collection when it is created. The Parameters Collection
is associated with a specific Command object, which uses the Collection to pass parameters in and out of
stored procedures and queries.
Parameters can be used to create Parameterized Commands. These commands are (after they have been
defined and stored) using parameters to alter some details of the command before it is executed. For
example, an SQL SELECT statement could use a parameter to define the criteria of a WHERE clause.
There are four types of parameters: input parameters, output parameters, input/output parameters and
return parameters.
Syntax
Properties
PropertyDescription
Attributes
Direction
Name
NumericScale
Sets or returns the number of digits stored to the right side of the decimal
point for a numeric value of a Parameter object
Precision
Size
Type
Value
Methods
Method
Description
Property Object
The ADO Property object represents a dynamic characteristic of an ADO object that is defined by the
provider.
Each provider that talks with ADO has different ways of interacting with ADO. Therefore, ADO needs to
store information about the provider in some way. The solution is that the provider gives specific
information (dynamic properties) to ADO. ADO stores each provider property in a Property object that is
again stored in the Properties Collection. The Collection is assigned to either a Command object,
Connection object, Field object, or a Recordset object.
ProgID
set objProperty=Server.CreateObject(ADODB.property)
Properties
Property Description
Attributes Returns the attributes of a Property object
Name
Type
Value
Syntax
Properties
Property
Description
ParentURL
RecordType
Source
Sets or returns the src parameter of the Open method of a Record object
State
Methods
Method
Description
Cancel
Close
CopyRecord
Returns a Recordset object where each row represents the files in the directory
MoveRecord
Open
Collections
Collection Description
Properties
Fields
Description
Count
Recordset Object
The ADO Recordset object is used to hold a set of records from a database table. A Recordset object
consist of records and columns (fields).
In ADO, this object is the most important and the most used object to manipulate data from a database.
ProgID
set objRecordset=Server.CreateObject(ADODB.recordset)
When you first open a Recordset, the current record pointer will point to the first record and the BOF
and EOF properties are False. If there are no records, the BOF and EOF property are True.
Recordset objects can support two types of updating:
Immediate updating - all changes are written immediately to the database once you call the
Update method.
Batch updating - the provider cache multiple changes and then send them to the database with
the UpdateBatch method.
In ADO there are 4 different cursor types defined:
Dynamic cursor - Allows you to see additions, changes, and deletions by other users.
Keyset cursor - Like a dynamic cursor, except that you cannot see additions by other users, and
it prevents access to records that other users have deleted. Data changes by other users will still
be visible.
Static cursor - Provides a static copy of a recordset for you to use to find data or generate
reports. Additions, changes, or deletions by other users will not be visible. This is the only type of
cursor allowed when you open a client-side Recordset object.
Forward-only cursor - Allows you to only scroll forward through the Recordset. Additions,
changes, or deletions by other users will not be visible.
The cursor type can be set by the CursorType property or by the CursorType parameter in the Open
method.
Note: Not all providers supports all methods or properties of the Recordset object.
Properties
Property
Description
AbsolutePage
Sets or returns a value that specifies the page number in the Recordset object
AbsolutePosition
Sets or returns a value that specifies the ordinal position of the current record in
the Recordset object
ActiveCommand
ActiveConnection
BOF
Returns true if the current record position is before the first record, otherwise
false
Bookmark
Sets or returns a bookmark. The bookmark saves the position of the current
record
CacheSize
CursorLocation
CursorType
DataMember
Sets or returns the name of the data member that will be retrieved from the
object referenced by the DataSource property
DataSource
EditMode
EOF
Returns true if the current record position is after the last record, otherwise false
Filter
Index
Sets or returns the name of the current index for a Recordset object
LockType
Sets or returns a value that specifies the type of locking when editing a record in a
Recordset
MarshalOptions
Sets or returns a value that specifies which records are to be returned back to the
server
MaxRecords
PageCount
PageSize
RecordCount
Sort
Source
Sets a string value or a Command object reference, or returns a String value that
indicates the data source of the Recordset object
State
Returns a value that describes if the Recordset object is open, closed, connecting,
executing or retrieving data
Status
Returns the status of the current record with regard to batch updates or other
bulk operations
StayInSync
Sets or returns whether the reference to the child records will change when the
parent record position changes
Methods
Method
Description
AddNew
Cancel
Cancels an execution
CancelBatch
CancelUpdate
Clone
Close
Closes a Recordset
Find
GetRows
GetString
Move
MoveFirst
MoveLast
MoveNext
MovePrevious
NextRecordset
Clears the current Recordset object and returns the next Recordset object by
looping through a series of commands
Open
Opens a database element that gives you access to records in a table, the
results of a query, or to a saved Recordset
Requery
Updates the data in a Recordset by re-executing the query that made the
original Recordset
Resync
Refreshes the data in the current Recordset from the original database
Save
Seek
Searches the index of a Recordset to find a record that matches the specified
values
Supports
Update
UpdateBatch
Saves all changes in a Recordset to the database. Used when working in batch
update mode
Events
Note: You cannot handle events using VBScript or JScript (only Visual Basic, Visual C++, and Visual
J++ languages can handle events).
Event
Description
EndOfRecordset
Triggered when you try to move to a record after the last record
FetchComplete
FetchProgress
FieldChangeComplete
MoveComplete
RecordChangeComplete
WillChangeRecord
WillChangeRecordset
WillMove
Collections
Collection Description
Fields
Properties
Description
Count
Description
Count
Syntax
Properties
Property
Description
CharSet
Sets or returns a value that specifies into which character set the contents are to be
translated. This property is only used with text Stream objects (type is adTypeText)
EOS
Returns whether the current position is at the end of the stream or not
LineSeparator Sets or returns the line separator character used in a text Stream object
Mode
Position
Sets or returns the current position (in bytes) from the beginning of a Stream object
Size
State
Type
Methods
Method
Description
Cancel
Close
CopyTo
Copies a specified number of characters/bytes from one Stream object into another
Stream object
Flush
Sends the contents of the Stream buffer to the associated underlying object
Read
Reads the entire stream or a specified number of bytes from a binary Stream object
ReadText
Reads the entire stream, a line, or a specified number of characters from a text
Stream object
SaveToFile
SetEOS
SkipLine
Write
WriteText