ObjectDataSource.TypeName Propiedad
Definición
Importante
Parte de la información hace referencia a la versión preliminar del producto, que puede haberse modificado sustancialmente antes de lanzar la versión definitiva. Microsoft no otorga ninguna garantía, explícita o implícita, con respecto a la información proporcionada aquí.
Obtiene o establece el nombre de la clase que representa el objeto ObjectDataSource.
public:
property System::String ^ TypeName { System::String ^ get(); void set(System::String ^ value); };
public string TypeName { get; set; }
member this.TypeName : string with get, set
Public Property TypeName As String
Valor de propiedad
Nombre de clase completo o parcial que identifica el tipo del objeto que representa ObjectDataSource. El valor predeterminado es una cadena vacía ("").
Ejemplos
En el ejemplo de código siguiente se muestra cómo un GridView control puede mostrar datos mediante un ObjectDataSource control en una página de formularios Web Forms. ObjectDataSource identifica un nombre de clase parcialmente o completo con su TypeName propiedad y un método al que se llama para recuperar datos con su SelectMethod propiedad . En tiempo de ejecución, se crea el objeto y se llama al método mediante la reflexión. El GridView control enumera a través de la IEnumerable colección devuelta por la SelectMethod propiedad y muestra los datos.
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - C# Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.CS.EmployeeLogic" />
</form>
</body>
</html>
<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.VB" Assembly="Samples.AspNet.VB" %>
<%@ Page language="vb" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>ObjectDataSource - Visual Basic Example</title>
</head>
<body>
<form id="Form1" method="post" runat="server">
<asp:gridview
id="GridView1"
runat="server"
datasourceid="ObjectDataSource1" />
<asp:objectdatasource
id="ObjectDataSource1"
runat="server"
selectmethod="GetAllEmployees"
typename="Samples.AspNet.VB.EmployeeLogic" />
</form>
</body>
</html>
En el ejemplo siguiente se muestra la clase a la que hace referencia el valor de propiedad TypeName .
namespace Samples.AspNet.CS {
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
//
// EmployeeLogic is a stateless business object that encapsulates
// the operations one can perform on a NorthwindEmployee object.
//
public class EmployeeLogic {
// Returns a collection of NorthwindEmployee objects.
public static ICollection GetAllEmployees () {
ArrayList al = new ArrayList();
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlDataSource sds
= new SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees");
try {
IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);
// Iterate through the Enumeration and create a
// NorthwindEmployee object for each ID.
foreach (DataRowView row in IDs) {
string id = row["EmployeeID"].ToString();
NorthwindEmployee nwe = new NorthwindEmployee(id);
// Add the NorthwindEmployee object to the collection.
al.Add(nwe);
}
}
finally {
// If anything strange happens, clean up.
sds.Dispose();
}
return al;
}
public static NorthwindEmployee GetEmployee(object anID) {
return new NorthwindEmployee(anID);
}
public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
bool retval = ne.Save();
if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
}
public static void DeleteEmployee(NorthwindEmployee ne) { }
}
public class NorthwindEmployee {
public NorthwindEmployee () {
ID = DBNull.Value;
lastName = "";
firstName = "";
title="";
titleOfCourtesy = "";
reportsTo = -1;
}
public NorthwindEmployee (object anID) {
this.ID = anID;
ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];
SqlConnection conn = new SqlConnection (cts.ConnectionString);
SqlCommand sc =
new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
" FROM Employees " +
" WHERE EmployeeID = @empId",
conn);
// Add the employee ID parameter and set its value.
sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
SqlDataReader sdr = null;
try {
conn.Open();
sdr = sc.ExecuteReader();
// This is not a while loop. It only loops once.
if (sdr != null && sdr.Read()) {
// The IEnumerable contains DataRowView objects.
this.firstName = sdr["FirstName"].ToString();
this.lastName = sdr["LastName"].ToString();
this.title = sdr["Title"].ToString();
this.titleOfCourtesy = sdr["TitleOfCourtesy"].ToString();
if (! sdr.IsDBNull(4)) {
this.reportsTo = sdr.GetInt32(4);
}
}
else {
throw new NorthwindDataException("Data not loaded for employee id.");
}
}
finally {
try {
if (sdr != null) sdr.Close();
conn.Close();
}
catch (SqlException) {
// Log an event in the Application Event Log.
throw;
}
}
}
private object ID;
private string lastName;
public string LastName {
get { return lastName; }
set { lastName = value; }
}
private string firstName;
public string FirstName {
get { return firstName; }
set { firstName = value; }
}
private string title;
public String Title {
get { return title; }
set { title = value; }
}
private string titleOfCourtesy;
public string Courtesy {
get { return titleOfCourtesy; }
set { titleOfCourtesy = value; }
}
private int reportsTo;
public int Supervisor {
get { return reportsTo; }
set { reportsTo = value; }
}
public bool Save () {
return true;
}
}
internal class NorthwindDataException: Exception {
public NorthwindDataException(string msg) : base (msg) { }
}
}
Imports System.Collections
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.UI
Imports System.Web.UI.WebControls
Namespace Samples.AspNet.VB
'
' EmployeeLogic is a stateless business object that encapsulates
' the operations you can perform on a NorthwindEmployee object.
' When the class is written in Visual Basic, you cannot use the Shared
' part.
Public Class EmployeeLogic
' Returns a collection of NorthwindEmployee objects.
Public Shared Function GetAllEmployees() As ICollection
Dim al As New ArrayList()
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim sds As New SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees")
Try
Dim IDs As IEnumerable = sds.Select(DataSourceSelectArguments.Empty)
' Iterate through the Enumeration and create a
' NorthwindEmployee object for each ID.
For Each row As DataRowView In IDs
Dim id As String = row("EmployeeID").ToString()
Dim nwe As New NorthwindEmployee(id)
' Add the NorthwindEmployee object to the collection.
al.Add(nwe)
Next
Finally
' If anything strange happens, clean up.
sds.Dispose()
End Try
Return al
End Function 'GetAllEmployees
Public Shared Function GetEmployee(anID As Object) As NorthwindEmployee
Return New NorthwindEmployee(anID)
End Function 'GetEmployee
Public Shared Sub UpdateEmployeeInfo(ne As NorthwindEmployee)
Dim retval As Boolean = ne.Save()
If Not retval Then
Throw New NorthwindDataException("UpdateEmployee failed.")
End If
End Sub
Public Shared Sub DeleteEmployee(ne As NorthwindEmployee)
End Sub
End Class
Public Class NorthwindEmployee
Public Sub New()
ID = DBNull.Value
aLastName = ""
aFirstName = ""
aTitle = ""
titleOfCourtesy = ""
reportsTo = - 1
End Sub
Public Sub New(anID As Object)
Me.ID = anID
Dim cts As ConnectionStringSettings = ConfigurationManager.ConnectionStrings("NorthwindConnection")
Dim conn As New SqlConnection(cts.ConnectionString)
Dim sc As New SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " & _
" FROM Employees " & _
" WHERE EmployeeID = @empId", conn)
' Add the employee ID parameter and set its value.
sc.Parameters.Add(New SqlParameter("@empId", SqlDbType.Int)).Value = Int32.Parse(anID.ToString())
Dim sdr As SqlDataReader = Nothing
Try
conn.Open()
sdr = sc.ExecuteReader()
' This is not a while loop. It only loops once.
If Not (sdr Is Nothing) AndAlso sdr.Read() Then
' The IEnumerable contains DataRowView objects.
Me.aFirstName = sdr("FirstName").ToString()
Me.aLastName = sdr("LastName").ToString()
Me.aTitle = sdr("Title").ToString()
Me.titleOfCourtesy = sdr("TitleOfCourtesy").ToString()
If Not sdr.IsDBNull(4) Then
Me.reportsTo = sdr.GetInt32(4)
End If
Else
Throw New NorthwindDataException("Data not loaded for employee id.")
End If
Finally
Try
If Not (sdr Is Nothing) Then
sdr.Close()
End If
conn.Close()
Catch se As SqlException
' Log an event in the Application Event Log.
Throw
End Try
End Try
End Sub
Private ID As Object
Private aLastName As String
Public Property LastName() As String
Get
Return aLastName
End Get
Set
aLastName = value
End Set
End Property
Private aFirstName As String
Public Property FirstName() As String
Get
Return aFirstName
End Get
Set
aFirstName = value
End Set
End Property
Private aTitle As String
Public Property Title() As String
Get
Return aTitle
End Get
Set
aTitle = value
End Set
End Property
Private titleOfCourtesy As String
Public Property Courtesy() As String
Get
Return titleOfCourtesy
End Get
Set
titleOfCourtesy = value
End Set
End Property
Private reportsTo As Integer
Public Property Supervisor() As Integer
Get
Return reportsTo
End Get
Set
reportsTo = value
End Set
End Property
Public Function Save() As Boolean
Return True
End Function 'Save
End Class
Friend Class NorthwindDataException
Inherits Exception
Public Sub New(msg As String)
MyBase.New(msg)
End Sub
End Class
End Namespace
Comentarios
Para crear una instancia del objeto al que se enlaza el ObjectDataSource control, el control usa la reflexión para cargar el tipo identificado por el nombre de tipo en tiempo de ejecución. Por lo tanto, el valor de la TypeName propiedad puede ser un tipo parcialmente calificado para el código que se encuentra en los directorios Bin o App_Code o un nombre de tipo completo para el código registrado en la caché global de ensamblados. Si usa la caché global de ensamblados, debe agregar la referencia adecuada a la assemblies
sección del archivo Machine.config o Web.config.
El tipo debe tener un constructor sin parámetros, a menos que controle el ObjectCreating evento para crear una instancia de él mismo. Se crea una instancia del tipo para cada llamada a los Selectmétodos , Update, Inserty Delete , si los métodos del tipo son métodos miembros. No se crea una instancia si los métodos son static
(Shared
en Visual Basic). Si el tipo implementa la IDisposable interfaz, se llama al Dispose método antes de destruir el objeto.