Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Manual de Laboratorio
Sintaxis y manejo básico de objetos y formularios
en C#
Página i
Information in this document is subject to change without notice. The example companies, organizations,
products, people, and events depicted herein are fictitious. No association with any real company, organization,
product, person or event is intended or should be inferred. Complying with all applicable copyright laws is the
responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced,
stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft
Corporation.
Microsoft may have patents, patent applications, trademarked, copyrights, or other intellectual property rights
covering subject matter in this document. Except as expressly provided in any written license agreement from
Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights,
or other intellectual property.
Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active Directory, BizTalk, SQL Server, SharePoint,
Outlook, PowerPoint, FrontPage, Visual Basic, Visual C++, Visual J++, Visual InterDev, Visual SourceSafe,
Visual C#, Visual J#, and Visual Studio are either registered trademarks or trademarks of Microsoft Corporation
in the U.S.A. and/or other countries.
Other product and company names herein may be the trademarks of their respective owners.
Página ii
Contenido
Página iii
Laboratorio: Sintaxis y Objetos de C#
Página 1
Ejercicio 1 – Creando la clase Persona
En este ejercicio crearás la clase persona con sus atributos y métodos necesarios.
La clase Persona contiene información relativa a una persona común, como nombres, apellidos, fecha
de nacimiento, etc. Esta clase será fundamental para el desarrollo de todo el laboratorio.
1. Ejecutar Visual Studio: desde el menú Start, seleccionar All Programs > Microsoft Visual
Studio 2005 > Microsoft Visual Studio 2005.
2. Desde el menú principal, seleccionar File > New > Project… para crear el Nuevo proyecto.
3. El diálogo de New Project aparecerá. En el árbol de Project Types seleccionar Visual C# >
Windows. En la sección Templates de la derecha seleccionar Windows Application. En el
textbox Name, escribir el nombre de tu nuevo proyecto:
LAB0201
Selecciona la ubicación deseada para tu proyecto. Deseleccionar el checkbox “Create directory
for solution”. Clickear OK para crear la solución.
4. En el explorador de la solución (Solution Explorer), presionar el botón derecho en el proyecto
Lab0201 y seleccionar Add > Class. Darle el nombre: clsPersona y presionar Enter. (Ver
figura).
Página 2
5. Modificar el namespace de la clase con: Curso.Lab0201
using System;
using System.Collections;
namespace Curso.Lab0201
{
/// <summary>
/// Implementación de la clase persona
/// </summary>
public class Persona
{ ….
Página 3
private string m_apellidopaterno;
private string m_apellidomaterno;
private DateTime m_fechanacimiento;
private int m_nrohijos;
private float m_sueldo;
private int m_docidentidad;
private string m_docidentidadnro;
private string m_sexo;
private int m_estadocivil;
private string m_telefono01;
private string m_telefono02;
private string m_direccion;
private string m_nacionalidad;
#endregion
/// <summary>
/// Constructor de la clase Persona. Aquí se inicializa todos los atributos de la clase
/// </summary>
public Persona()
{
// Inicialización de atributos
m_id = 0;
m_nombres = String.Empty;
m_apellidopaterno = String.Empty;
m_apellidomaterno = String.Empty;
m_fechanacimiento = DateTime.MinValue;
m_nrohijos = 0;
m_sueldo = 0;
m_docidentidad = 0;
m_docidentidadnro = String.Empty;
m_sexo = String.Empty;
m_estadocivil = 0;
m_telefono01 = String.Empty;
m_telefono02 = String.Empty;
m_direccion = String.Empty;
m_nacionalidad = String.Empty;
}
Página 4
public int NroHijos
{
get { return m_nrohijos; }
set { m_nrohijos = value; }
}
Página 5
resumen = resumen + System.Environment.NewLine + string.Format("Documento de Identidad = {0}
{1}", m_docidentidad, m_docidentidadnro);
resumen = resumen + System.Environment.NewLine + string.Format("Sexo = {0}", m_sexo);
resumen = resumen + System.Environment.NewLine + string.Format("Estado Civil = {0}",
m_estadocivil);
resumen = resumen + System.Environment.NewLine + string.Format("Teléfonos = {0} / {1}",
m_telefono01, m_telefono02);
resumen = resumen + System.Environment.NewLine + string.Format("Dirección = {0}",
m_direccion);
resumen = resumen + System.Environment.NewLine + string.Format("Nacionalidad = {0}",
m_nacionalidad);
return resumen;
}
Página 6
Ejercicio 2 – Mostrando la información de la persona
En este ejercicio crearás el formulario para mostrar el resumen informativo de la persona, es decir
invocarás el método ObtenerResumen() de la clase persona para mostrar su información resumida en
un control TextBox.
En esta tarea crearás un formulario el cual tendrá un texbox para mostrar el resumen de la persona y
un botón para modificar su información. La funcionalidad del botón se implementará en el siguiente
ejercicio.
1. En el menú contextual del proyecto (botón derecho en el proyecto Lab0201) seleccionar Add >
Windows Form y darle el nombre frmMantPersonas.
2. En el menú contextual del formulario frmMantPersonas seleccionar View Code y agregar el
namespace de la clase persona mediante el código:
using Curso.Lab0201;
3. Agregar el objeto principal Persona que se utilizará en la toda la aplicación, como un atributo de
la clase frmMantPersonas , debiendo quedar de la siguiente manera:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Curso.Lab0201;
namespace Lab0201
{
public partial class frmMantPersonas : Form
{
// Objeto principal persona
private Persona MiObjetoPersona;
public frmMantPersona()
{
InitializeComponent();
}
}
}
4. En el menú contextual del formulario frmMantPersonas seleccionar View Designer para ver el
formulario en modo diseño. Debes modificarlo hasta quedar de la siguiente manera:
Página 7
Como puedes ver, se agregó un textbox (txtResumenPersona) con la propiedad MultiLine y un
botón simple con el texto “Editar Persona” (btnEditarPersona).
5. Agregar el evento Load al formulario: En la ventana propiedades hacer click en el rayo amarillo
para ver los eventos, ubicar la propiedad Load y darle doble click. (Ver figura)
Página 8
private void frmMantPersonas_Load(object sender, EventArgs e)
{
Este código creará una persona de ejemplo la cual será mostrada en el formulario.
7. Crear el evento click para el botón btnEditarPersona (ver paso 5) y agregar el siguiente código:
private void btnEditarPersona_Click(object sender, EventArgs e)
{
// Mostrar el resumen de la persona
this.MostrarResumenPersona();
}
9. Para establecer el formulario de inicio del programa, abrir la clase Program.cs y modificar la
sentencia existente con el siguiente código:
Página 9
Application.Run(new frmMantPersonas());
10. Ejecutar el programa presionando Ctrl + F5 y ver el resultado.
Página 10
Ejercicio 3 – Modificando la información de la persona
En este ejercicio crearás el formulario que permitirá modificar la información de la persona y guardarla
nuevamente en el objeto Persona.
Botones:
btnGuardar
btnCancelar
Página 11
txtNacionalidad
txtDireccion, con la propiedad MultiLine: True
txtTelefono01
txtTelefono02
txtSueldo
txtNroHijos
Combos (ComboBox):
cboEstadoCivil, con la propiedad DropDownStyle: DropDownList
cboTipoDocumento, con la propiedad DropDownStyle: DropDownList
2. Agregar el contenido a los Combos: Utilizar la propiedad Items para agregar elementos a los
combos (ver figura).
Combo: cboTipoDocumento
Combo: cboEstadoCivil
Página 12
3. En el formulario, agregar el código para referenciar al namespace de la clase persona:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Curso.Lab0201;
public frmEditarPersona()
{
InitializeComponent();
}
txtID.Text = objPersona.ID.ToString();
txtNombres.Text = objPersona.Nombres;
txtApellidoPaterno.Text = objPersona.ApellidoPaterno;
txtApellidoMaterno.Text = objPersona.ApellidoMaterno;
dtpFechaNacimiento.Value = objPersona.FechaNacimiento;
txtNroHijos.Text = objPersona.NroHijos.ToString();
txtSueldo.Text = objPersona.Sueldo.ToString();
cboTipoDocumento.SelectedIndex = objPersona.DocIdentidad - 1;
txtNroDocumento.Text = objPersona.DocIdentidadNro;
txtSexo.Text = objPersona.Sexo;
cboEstadoCivil.SelectedIndex = objPersona.EstadoCivil - 1;
txtTelefono01.Text = objPersona.Telefono01;
txtTelefono02.Text = objPersona.Telefono02;
txtDireccion.Text = objPersona.Direccion;
txtNacionalidad.Text = objPersona.Nacionalidad;
}
Página 13
7. Agregar el método GuardarValores() al formulario:
objPersona.ID = int.Parse(txtID.Text);
objPersona.Nombres = txtNombres.Text;
objPersona.ApellidoPaterno = txtApellidoPaterno.Text;
objPersona.ApellidoMaterno = txtApellidoMaterno.Text;
objPersona.FechaNacimiento = dtpFechaNacimiento.Value;
objPersona.NroHijos = int.Parse(txtNroHijos.Text);
objPersona.Sueldo = float.Parse(txtSueldo.Text);
objPersona.DocIdentidad = cboTipoDocumento.SelectedIndex + 1;
objPersona.DocIdentidadNro = txtNroDocumento.Text;
objPersona.Sexo = txtSexo.Text;
objPersona.EstadoCivil = cboEstadoCivil.SelectedIndex + 1;
objPersona.Telefono01 = txtTelefono01.Text;
objPersona.Telefono02 = txtTelefono02.Text;
objPersona.Direccion = txtDireccion.Text;
objPersona.Nacionalidad = txtNacionalidad.Text;
}
// Cerrar el formulario
this.Close();
}
Página 14
private void btnEditarPersona_Click(object sender, EventArgs e)
{
// Crear el formulario de edicion
frmEditarPersona formulario = new frmEditarPersona();
// Mostrar el formulario
formulario.ShowDialog();
Página 15
Página 16