Vous êtes sur la page 1sur 31

E-PORTAFOLIO

PROGRAMACIÓN II
PERIODO I, CICLO I, 2018

Jonathan Enrique Vanegas Coreas


UNIVERSIDAD CATÓLICA DE EL SALVADOR
E-PORTAFOLIO PROGRAMACIÓN II

Tabla de contenido
PRÁCTICA 1: INTRODUCCIÓN A LAS APLICACIONES CON INTERFAZ GRÁFICA. .................................. 3
Objetivos. ........................................................................................................................................ 3
Aplicación para conversión de dólar a otras monedas. .................................................................. 3
Aplicación para conversión de decimal a otras bases de numeración. .......................................... 4
Aplicación para agregar o quitar elementos de una lista. .............................................................. 5
Aplicación para convertir temperaturas de grados centígrados a Fahrenheit. .............................. 6
PRÁCTICA 2: ESTRUCTURAS DE CONTNROL DE SELECCIÓN. ............................................................... 7
Objetivos: ........................................................................................................................................ 7
Aplicación para convertir números entre 1 y 10 a romano. ........................................................... 8
Aplicación para calcular el valor a pagar por la compra de un producto, calculando el descuento
seleccionado.................................................................................................................................... 9
Aplicación para convertir entre unidades de longitud: pulgadas, pies y yardas. ......................... 11
Aplicación para capturar datos personales en cuadros de texto (TextBox) validados usando
Expresiones Regulares................................................................................................................... 13
PRÁCTICA 3: ESTRUCTURAS DE CONTROL DE REPETICIÓN. .............................................................. 16
Objetivos: ...................................................................................................................................... 16
Aplicación para generar en un ListBox la tabla de multiplicar especificada por el usuario. ......... 17
Aplicación para agregar a un ListBox el alfabeto en mayúsculas, al hacer clic en el botón
Mostrar.......................................................................................................................................... 18
Aplicación que realiza 5000 lanzamientos de un dado, y agrega cada resultado al ListBox y al
final muestra en MessageBox la cantidad de veces que logró obtener el número 6. .................. 19
Aplicación para generar 100 números aleatorios (entre 10 y 99) y mostrarlos en un
DataGridView de 10 filas x 10 columnas y programar el botón Buscar para que permita buscar el
numero indicado en el TextBox y los resalte con otro color......................................................... 20
Aplicación para calcular una planilla de pagos por horas trabajadas. .......................................... 21
PRÁCTICA 4: INTRODUCCIÓN A LAS FUNCIONES. ............................................................................. 23
Objetivos: ...................................................................................................................................... 23
Aplicación que captura 4 números en diferentes cuadros de texto, y crea una función que recibe
los números y retorna la sumatoria de dichos números para ser mostrada en una etiqueta. .... 23
Aplicación que almacena en un ListBox cualquier cantidad de números ingresados por un cuadro
de texto, que posee una función para buscar un determinado número y que indique cuantas
veces aparece dicho número en la lista. ....................................................................................... 24
Aplicación que posee una función recursiva para calcular el Fibonacci de un número
determinado capturado en un cuadro de texto. .......................................................................... 25

1
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación que posee una función “mayor” con 2 versiones, la primera para devolver el mayor
de dos números enteros y la segunda para devolver el mayor de tres números enteros. .......... 26
PRÁCTICA 5: ARREGLOS..................................................................................................................... 28
Objetivos: ...................................................................................................................................... 28
Aplicación que almacena en un arreglo los nombres de 10 vendedores, y que los muestra en un
ListBox y provee las opciones para ordenar ascendentemente, ordenar descendentemente,
quitar elementos de la lista (y del arreglo) y buscar el nombre de un vendedor (si se encuentra
lo seleccionará automáticamente en la lista y si no se encuentra mostrará un mensaje). .......... 28

2
E-PORTAFOLIO PROGRAMACIÓN II

PRÁCTICA 1: INTRODUCCIÓN A LAS APLICACIONES CON INTERFAZ


GRÁFICA.

Objetivos.
• Conocer la estructura de un proyecto Windows Forms.
• Identificar los tipos de controles disponibles para Windows Forms.
• Crear aplicaciones Windows Forms utilizando propiedades, métodos y eventos comunes.

Ejercicios para resolver: deberá colocar en el e-portafolio el formulario y el código de Visual C#


requerido para el funcionamiento del formulario.

Indicaciones: en Visual Studio .NET crear un proyecto de tipo Aplicación Windows Forms… y crear un
formulario por cada uno de los siguientes ejercicios.

Aplicación para conversión de dólar a otras monedas.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_1 : Form
{
public Ejercicio_1()
{
InitializeComponent();
}

private void btnConvertir_Click(object sender, EventArgs e)


{
double usd = Convert.ToDouble(txtDolar.Text);
double eur, chf, jpy, gbp;
eur = usd * 0.81;
chf = usd * 0.95;
jpy = usd * 109.95;
gbp = usd * 0.70;
txtEuro.Text = string.Format("{0:N2}", eur);
txtFranco.Text = string.Format("{0:N2}", chf);
txtYen.Text = string.Format("{0:N2}", jpy);
txtLibra.Text = string.Format("{0:N2}", gbp);
}

private void btnSalir_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

3
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para conversión de decimal a otras bases de numeración.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_2 : Form
{
public Ejercicio_2()
{
InitializeComponent();
}

private void bttnConvertir_Click(object sender, EventArgs e)


{
int decim = Convert.ToInt32(txtDecimal.Text);
txtBinario.Text = Convert.ToString(decim, 2);
txtOctal.Text = Convert.ToString(decim, 8);
txtHexadecimal.Text = Convert.ToString(decim, 16);
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

4
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para agregar o quitar elementos de una lista.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_3 : Form
{
public Ejercicio_3()
{
InitializeComponent();
}

private void bttnAgregar_Click(object sender, EventArgs e)


{
string elemen = Convert.ToString(txtElmentos.Text);
lstbxElementos.Items.Add(elemen);
}

private void bttnQuitar_Click(object sender, EventArgs e)


{
lstbxElementos.Items.Remove(lstbxElementos.SelectedItem);
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

5
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para convertir temperaturas de grados centígrados a Fahrenheit.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_4 : Form
{
public Ejercicio_4()
{
InitializeComponent();
}

private void bttnConvertir_Click(object sender, EventArgs e)


{
double cel = Convert.ToDouble(txtCelsius.Text);
double fah;
fah = cel * 9 / 5 + 32;
txtFahrenheit.Text = string.Format("{0:N2}", fah);
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}

private void bttnMasUno_Click(object sender, EventArgs e)


{

6
E-PORTAFOLIO PROGRAMACIÓN II

double cel = Convert.ToDouble(txtCelsius.Text)+1;


double fah;
txtCelsius.Text = string.Format("{0:N2}", cel);
fah = cel * 1.8 + 32;
txtFahrenheit.Text = string.Format("{0:N2}", fah);
}

private void bttnMenosUno_Click(object sender, EventArgs e)


{
double cel = Convert.ToDouble(txtCelsius.Text) - 1;
double fah;
txtCelsius.Text = string.Format("{0:N2}", cel);
fah = cel * 1.8 + 32;
txtFahrenheit.Text = string.Format("{0:N2}", fah);
}
}
}

PRÁCTICA 2: ESTRUCTURAS DE CONTNROL DE SELECCIÓN.

Objetivos:
• Aplicar el uso de estructuras de control selectivas.
• Validar el control TextBox usando el evento KeyPress.
• Validar el control TextBox usando los eventos Validating y Validated.
• Validar el control TextBox usando Expresiones Regulares.

Ejercicios para resolver: deberá colocar en el e-portafolio el formulario y el código de Visual C#


requerido para el funcionamiento del formulario.

Indicaciones: en Visual Studio .NET crear un proyecto de t ipo Aplicación Windows


Forms… y crear un formulario por cada uno de los siguientes ejercicios.

7
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para convertir números entre 1 y 10 a romano.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_5 : Form
{
public Ejercicio_5()
{
InitializeComponent();
}

private void bttnConvertir_Click(object sender, EventArgs e)


{
int num = Convert.ToInt32(txtNumero.Text);
string resul;
String[] Unidad = { "", "I", "II", "III", "IV", "V", "VI", "VII",
"VIII", "IX" };
String[] Decena = { "", "X"};
int un = num% 10;
int de = (num / 10) % 10;
if (num >= 10)
{
resul=(Decena[de] + Unidad[un]);
lblResultado.Text = string.Format("Equivale a " + resul + " en
romano.");
}
else
{
resul= (Unidad[num]);
lblResultado.Text = string.Format("Equivale a " + resul + " en
romano.");
}
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

8
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para calcular el valor a pagar por la compra de un producto, calculando el


descuento seleccionado.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_6 : Form
{
public Ejercicio_6()
{
InitializeComponent();
}

private void bttnCalcular_Click(object sender, EventArgs e)


{
double can = Convert.ToDouble(txtCantidad.Text);
double prec = Convert.ToDouble(txtPrecio.Text);
double total, desc,ntotal;
if (rdbttn0.Checked)
{
total = can * prec;
txtDescuento.Text = ("Sin Descuento");
txtTotal.Text = string.Format("{0:C2}",total);
}
else if (rdbttn5.Checked)
{

9
E-PORTAFOLIO PROGRAMACIÓN II

total = can * prec;


desc = (total * 0.05);
ntotal = total - desc;
txtDescuento.Text = string.Format("{0:C2}", desc);
txtTotal.Text = string.Format("{0:C2}", ntotal);
}
else if (rdbttn10.Checked)
{
total = can * prec;
desc = (total * 0.10);
ntotal = total - desc;
txtDescuento.Text = string.Format("{0:C2}", desc);
txtTotal.Text = string.Format("{0:C2}", ntotal);
}
else if (rdbttn15.Checked)
{
total = can * prec;
desc = (total * 0.15);
ntotal = total - desc;
txtDescuento.Text = string.Format("{0:C2}", desc);
txtTotal.Text = string.Format("{0:C2}", ntotal);
}
else if (rdbttn20.Checked)
{
total = can * prec;
desc = (total * 0.20);
ntotal = total - desc;
txtDescuento.Text = string.Format("{0:C2}", desc);
txtTotal.Text = string.Format("{0:C2}", ntotal);
}
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}

private void bttnLimpiar_Click(object sender, EventArgs e)


{
txtCantidad.Clear();
txtPrecio.Clear();
txtDescuento.Clear();
txtTotal.Clear();
txtCantidad.Focus();
}
}
}

10
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para convertir entre unidades de longitud: pulgadas, pies y yardas.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_7 : Form
{
public Ejercicio_7()
{
InitializeComponent();
}

private void bttnConvert_Click(object sender, EventArgs e)


{
double longi = Convert.ToDouble(txtbxIntrlong.Text);
double total;
if (lstBxDe.Text=="Pulgadas" && lstBxA.Text=="Pulgadas")
{
total = longi * 1;
txtBxLongConve.Text = string.Format("{0}", total);
}
else if (lstBxDe.Text=="Pulgadas" && lstBxA.Text=="Pies")
{
total = longi*0.833333;
txtBxLongConve.Text = string.Format("{0:N2}", total);
}
else if (lstBxDe.Text=="Pulgadas" && lstBxA.Text=="Yardas")
{
total = longi*0.0277777666667;

11
E-PORTAFOLIO PROGRAMACIÓN II

txtBxLongConve.Text = string.Format("{0:N2}", total);


}
else if (lstBxDe.Text=="Pies" && lstBxA.Text=="Pulgadas")
{
total = longi*12;
txtBxLongConve.Text = string.Format("{0}", total);
}
else if (lstBxDe.Text=="Pies" && lstBxA.Text=="Pies")
{
total = longi * 1;
txtBxLongConve.Text = string.Format("{0}", total);
}
else if (lstBxDe.Text=="Pies" && lstBxA.Text=="Yardas")
{
total = longi * 0.333333;
txtBxLongConve.Text = string.Format("{0:N2}", total);
}
else if (lstBxDe.Text=="Yardas" && lstBxA.Text=="Pulgadas")
{
total = longi * 36;
txtBxLongConve.Text = string.Format("{0}", total);
}
else if (lstBxDe.Text=="Yardas" && lstBxA.Text=="Pies")
{
total = longi * 3;
txtBxLongConve.Text = string.Format("{0}", total);
}
else if(lstBxDe.Text=="Yardas" && lstBxA.Text=="Yardas")
{
total = longi * 1;
txtBxLongConve.Text = string.Format("{0}", total);
}
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}
}
}

12
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para capturar datos personales en cuadros de texto (TextBox) validados


usando Expresiones Regulares
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace Programacion_2
{
public partial class Ejercicio_8 : Form
{
public Ejercicio_8()
{
InitializeComponent();
}

private void mskdTxtBxCorreo_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-
.]\\w+)*");
if (!formato.IsMatch(mskdTxtBxCorreo.Text))
{
e.Cancel = true;
mskdTxtBxCorreo.SelectAll();
erroremal.SetError(mskdTxtBxCorreo, "Por favor ingrese un correo
valido");
}
}

private void mskdTxtBxCorreo_Validated(object sender, EventArgs e)


{
erroremal.Clear();
}

private void txtBxNombre_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("[a-zA-ZñÑ\\s]{2,50}");
if (!formato.IsMatch(txtBxNombre.Text))
{
e.Cancel = true;
txtBxNombre.SelectAll();
errornombre.SetError(txtBxNombre, "Ingrese el nombre
correctamente");
}
}

private void txtBxNombre_Validated(object sender, EventArgs e)


{
errornombre.Clear();
}

13
E-PORTAFOLIO PROGRAMACIÓN II

private void txtBxNombre_KeyPress(object sender, KeyPressEventArgs e)


{
if (char.IsLetter(e.KeyChar))
{
e.Handled = false;
}
else if (char.IsSeparator(e.KeyChar))
{
e.Handled = false;
}
else if (char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}

private void mskdTxtBxFecha_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("^([0-2][0-9]|3[0-1])(\\/|-)(0[1-9]|1[0-
2])\\2(\\d{4})$");
if (!formato.IsMatch(mskdTxtBxFecha.Text))
{
e.Cancel = true;
mskdTxtBxFecha.SelectAll();
errorfecha.SetError(mskdTxtBxFecha, "Ingrese fecha correcta de la
forma DD/MM/AAAA");
}
}

private void mskdTxtBxFecha_Validated(object sender, EventArgs e)


{
errorfecha.Clear();
}

private void mskdTxtBxFecha_KeyPress(object sender, KeyPressEventArgs e)


{
if (char.IsNumber(e.KeyChar))
{
e.Handled = false;
}
else if (char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}

private void mskdTxtBxDui_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("^([0-9]{8})-([0-9]{1})$");
if (!formato.IsMatch(mskdTxtBxDui.Text))

14
E-PORTAFOLIO PROGRAMACIÓN II

{
e.Cancel = true;
mskdTxtBxDui.SelectAll();
errordui.SetError(mskdTxtBxDui, "Ingrese un numero de Dui
Correcto");
}
}

private void mskdTxtBxDui_Validated(object sender, EventArgs e)


{
errordui.Clear();
}

private void mskdTxtBxNit_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("^([0-9]{4})-([0-9]{6})-([0-9]{3})-([0-
9]{1})$");
if (!formato.IsMatch(mskdTxtBxNit.Text))
{
e.Cancel = true;
mskdTxtBxNit.SelectAll();
errornit.SetError(mskdTxtBxNit, "Ingrese un numero de Nit
correcto");
}
}

private void mskdTxtBxNit_Validated(object sender, EventArgs e)


{
errornit.Clear();
}

private void mskdTxtBxTel_Validating(object sender, CancelEventArgs e)


{
Regex formato = new Regex("^([0-9]{4})-([0-9]{4})$");
if (!formato.IsMatch(mskdTxtBxTel.Text))
{
e.Cancel = true;
mskdTxtBxTel.SelectAll();
errortel.SetError(mskdTxtBxTel, "Ingrese un numero de telefono
correcto");
}
}

private void mskdTxtBxTel_Validated(object sender, EventArgs e)


{
errortel.Clear();
}

private void Ejercicio_8_FormClosing(object sender, FormClosingEventArgs e)


{
e.Cancel = false;
}

private void bttnSalir_Click(object sender, EventArgs e)


{
this.Close();
}

15
E-PORTAFOLIO PROGRAMACIÓN II

private void bttnAceptar_Click(object sender, EventArgs e)


{
if (txtBxNombre.Text.Length==0||
mskdTxtBxFecha.Text.Length==0||mskdTxtBxDui.Text.Length==0||
mskdTxtBxNit.Text.Length==0||mskdTxtBxTel.Text.Length==0||
mskdTxtBxCorreo.Text.Length==0)
{
MessageBox.Show("Faltan campos por llenar");
}
else
{
MessageBox.Show("Datos Correctos");
}
}
}
}

PRÁCTICA 3: ESTRUCTURAS DE CONTROL DE REPETICIÓN.

Objetivos:
• Aplicar las estructuras de control repetitivas.
• Utilizar las estructuras de control de repetición en aplicaciones Windows Form.

Ejercicios para resolver: deberá colocar en el e-portafolio el formulario y el código de Visual C#


requerido para el funcionamiento del formulario.

Indicaciones: en Visual Studio .NET crear un proyecto de tipo Aplicación Windows


Forms… y crear un formulario por cada uno de los sig uientes ejercicios.

16
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para generar en un ListBox la tabla de multiplicar especificada por el


usuario.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_9 : Form
{
public Ejercicio_9()
{
InitializeComponent();
}

private void bttnGener_Click(object sender, EventArgs e)


{
int numero = Convert.ToInt32(txtBxNumero.Text);
int total;
for (int i = 1; i <=10; i++)
{
total = i*numero;
lstBxTablas.Items.Add(numero+" X "+i+" = "+total);
}
}
}
}

17
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para agregar a un ListBox el alfabeto en mayúsculas, al hacer clic en el


botón Mostrar.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_10 : Form
{
public Ejercicio_10()
{
InitializeComponent();
}

private void bttnGene_Click(object sender, EventArgs e)


{
char letra;
for (int i = 65; i <=90; i++)
{
letra = Convert.ToChar(i);
lstBxAlfabe.Items.Add(letra);
}
}
}
}

18
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación que realiza 5000 lanzamientos de un dado, y agrega cada resultado al


ListBox y al final muestra en MessageBox la cantidad de veces que logró obtener el
número 6.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_11 : Form
{
public Ejercicio_11()
{
InitializeComponent();
}

private void bttnLanzar_Click(object sender, EventArgs e)


{
int dado=0,conta=0,num6=0;
Random num = new Random();
lstBxLanza.Items.Clear();
const int lanzamientos = 5000;
while (conta<lanzamientos)
{
dado = num.Next(1, 15);
conta++;
lstBxLanza.Items.Add(dado);
if (dado==6)
{
num6++;
}
}
MessageBox.Show("el numero 6 se obtubo "+num6+" veces");
}
}
}

19
E-PORTAFOLIO PROGRAMACIÓN II

Aplicación para generar 100 números aleatorios (entre 10 y 99) y mostrarlos en un


DataGridView de 10 filas x 10 columnas y programar el botón Buscar para que
permita buscar el numero indicado en el TextBox y los resalte con otro color.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_12 : Form
{
public Ejercicio_12()
{
InitializeComponent();
}

private void Ejercicio_12_Load(object sender, EventArgs e)


{
DtGrdVwNum.Size = new Size(210, 220);
DtGrdVwNum.AllowUserToAddRows = false;
DtGrdVwNum.ScrollBars = ScrollBars.None;
DtGrdVwNum.ColumnCount = 10;
DtGrdVwNum.ColumnHeadersVisible = false;
DtGrdVwNum.RowHeadersVisible = false;
DtGrdVwNum.AutoSizeColumnsMode =
DataGridViewAutoSizeColumnsMode.AllCells;
Random num = new Random();
for (int x = 0; x < 10; x++)
{
DtGrdVwNum.Rows.Add();
for (int y = 0; y < 10; y++)
{
DtGrdVwNum.Rows[x].Cells[y].Value = num.Next(10, 100);
}
}
DtGrdVwNum.ClearSelection();
}

private void bttnbuscar_Click(object sender, EventArgs e)


{
int num = Convert.ToInt32(txtBxnum.Text);

for (int f = 0; f < 10; f++)


{
for (int c = 0; c < 10; c++)
{
string valor;
valor =DtGrdVwNum.Rows[f].Cells[c].Value.ToString();
if (num==Convert.ToInt32(valor))
{

20
E-PORTAFOLIO PROGRAMACIÓN II

DtGrdVwNum.Rows[f].Cells[c].Style.BackColor = Color.Yellow;
}
}
}
}
}
}

Aplicación para calcular una planilla


de pagos por horas trabajadas.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_13 : Form
{
public Ejercicio_13()
{
InitializeComponent();
}

private void bttnagreg_Click(object sender, EventArgs e)


{
string nombre = Convert.ToString(txtBxnombre.Text);
int hora = Convert.ToInt32(txtBxhoras.Text);
double valor = Convert.ToDouble(txtBxvalorh.Text);

21
E-PORTAFOLIO PROGRAMACIÓN II

double sub, total,iva;


sub = hora * valor;
iva = sub * 0.13;
total =sub + iva;
dtGrdVwtabla.Rows.Add(nombre, hora, "$ "+valor,"$ "+sub, "$ " + iva, "$
" + total);
total = 0;
dtGrdVwtabla.ClearSelection();
foreach (DataGridViewRow celda in dtGrdVwtabla.Rows)
{
total += Convert.ToDouble(celda.Cells["Columntota"].Value);
}
lblplanti.Text = string.Format("{0:C2}", total);
txtBxnombre.Clear();
txtBxhoras.Clear();
txtBxvalorh.Clear();
txtBxnombre.Focus();
}

private void bttnlimpi_Click(object sender, EventArgs e)


{
dtGrdVwtabla.Rows.Clear();
}
}

22
E-PORTAFOLIO PROGRAMACIÓN II

PRÁCTICA 4: INTRODUCCIÓN A LAS FUNCIONES.

Objetivos:
• Crear funciones propias o personalizadas por el programador
• Programar funciones con listas de argumentos de longitud variable
• Aplicar la recursividad en la programación de funciones
• Aplicar la sobrecarga de funciones

Ejercicios para resolver: deberá colocar en el e-portafolio el formulario y el código de Visual C#


requerido para el funcionamiento del formulario.

Indicaciones: en Visual Studio .NET crear un proyecto de tipo Aplicación Windows


Forms… y crear un formulario por cada uno de los siguientes ejercicios.

Aplicación que captura 4 números en diferentes cuadros de texto, y crea una


función que recibe los números y retorna la sumatoria de dichos números para ser
mostrada en una etiqueta.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2
{
public partial class Ejercicio_14 : Form
{
public Ejercicio_14()
{
InitializeComponent();
}
public static int Suma(int num1,int num2,int num3, int num4)
{
int suma;
suma = num1 + num2 + num3 + num4;
return suma;
}

private void bttnsuma_Click(object sender, EventArgs e)


{
int n1 = Convert.ToInt32(txtBxnum1.Text);
int n2 = Convert.ToInt32(txtBxnum2.Text);
int n3 = Convert.ToInt32(txtBxnum3.Text);
int n4 = Convert.ToInt32(txtBxnum4.Text);
int suma;
suma = Suma(n1, n2, n3, n4);
label5.Text = string.Format("{0}", suma);

23
E-PORTAFOLIO PROGRAMACIÓN II

}
}
}

Aplicación que almacena en un ListBox cualquier cantidad de números ingresados


por un cuadro de texto, que posee una función para buscar un determinado número
y que indique cuantas veces aparece dicho número en la lista.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2P1
{
public partial class Ejercicio_15 : Form
{
public Ejercicio_15()
{
InitializeComponent();
}
public static int Buscar(int numer,params string[] numeros)
{
int busc = 0;
foreach (string numero in numeros)
{
if (Convert.ToInt32(numero)==numer)
{
busc++;
}
}
return busc;

24
E-PORTAFOLIO PROGRAMACIÓN II

}
private void bttnagreg_Click(object sender, EventArgs e)
{
lstBxnume.Items.Add(txtBxnumero.Text);
txtBxnumero.Clear();
}

private void bttnbusc_Click(object sender, EventArgs e)


{
int numbus = Convert.ToInt32(txtBxbusc.Text);
int buscar;
string[] num = new string[lstBxnume.Items.Count];
lstBxnume.Items.CopyTo(num, 0);
buscar = Buscar(numbus, num);
MessageBox.Show("El numero " + numbus + " se encontro " + buscar+"
veces.");
}
}
}

Aplicación que posee una función recursiva para calcular el Fibonacci de un número
determinado capturado en un cuadro de texto.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2P1

25
E-PORTAFOLIO PROGRAMACIÓN II

{
public partial class Ejercicio_16 : Form
{
public Ejercicio_16()
{
InitializeComponent();
}

public static int Fibonacci(int num)


{
if (num == 1 || num == 0)
{
return num;
}
else
{
return Fibonacci(num - 1) + Fibonacci(num-2);
}
}
private void bttncalc_Click(object sender, EventArgs e)
{
int num = Convert.ToInt32(txtBxnum.Text);
for (int i = 0; i <= num-1; i++)
{
txtBxfibo.Text = string.Format("{0}", Fibonacci(i));
}
txtBxnum.Clear();
txtBxnum.Focus();
}
}
}

Aplicación que posee una función “mayor” con 2 versiones, la primera para devolver
el mayor de dos números enteros y la segunda para devolver el mayor de tres
números enteros.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;

26
E-PORTAFOLIO PROGRAMACIÓN II

using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion_2P1
{
public partial class Ejercicio_17 : Form
{
public Ejercicio_17()
{
InitializeComponent();
}

public static int Mayor(int num1,int num2)


{
if (num1<num2)
{
return num2;
}
else
{
return num1;
}
}
public static int Mayor(int num1,int num2,int num3)
{
if (num1>num2 && num1>num3)
{
return num1;
}
else if (num2 > num1 && num2 > num3)
{
return num2;
}
else
{
return num3;
}
}
private void bttnmayor_Click(object sender, EventArgs e)
{
int num1 = Convert.ToInt32(txtBxnum1.Text);
int num2 = Convert.ToInt32(txtBxnum2.Text);
label5.Text = string.Format("{0}", Mayor(num1, num2));
if (!string.IsNullOrEmpty(txtBxnum3.Text))
{
int num3 = Convert.ToInt32(txtBxnum3.Text);
label5.Text = string.Format("{0}", Mayor(num1, num2, num3));
}
}
}
}

27
E-PORTAFOLIO PROGRAMACIÓN II

PRÁCTICA 5: ARREGLOS

Objetivos:
• Crear arreglos: unidimensionales, bidimensionales (rectangulares y dentados)
• Realizar ordenamiento y búsqueda en arreglos
• Pasar arreglos a parámetros de funciones (métodos)

Ejercicios para resolver: deberá colocar en el e-portafolio el formulario y el código de Visual C#


requerido para el funcionamiento del formulario.

Indicaciones: en Visual Studio .NET crear un proyecto de tipo Aplicación Windows


Forms… y crear un formulario por cada uno de los siguientes ejercicios.

Aplicación que almacena en un arreglo los nombres de 10 vendedores, y que los


muestra en un ListBox y provee las opciones para ordenar ascendentemente, ordenar
descendentemente, quitar elementos de la lista (y del arreglo) y buscar el nombre de
un vendedor (si se encuentra lo seleccionará automáticamente en la lista y si no se
encuentra mostrará un mensaje).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Programacion2_Guia5
{

28
E-PORTAFOLIO PROGRAMACIÓN II

public partial class Ejercicio_1P5 : Form


{
public Ejercicio_1P5()
{
InitializeComponent();
}
string[] vende = {"Juana","Pedro","Jonathan","Maria","Mario","Luis",
"Flor","Carlos","Jennifer","Johanna"};

private void Ejercicio_1P5_Load(object sender, EventArgs e)


{
for (int i = 0; i < 10; i++)
{
lstBxvende.Items.Add(vende[i]);
}
}

private void bttnaz_Click(object sender, EventArgs e)


{
lstBxvende.Items.Clear();
Array.Sort(vende);
for (int i = 0; i < 10; i++)
{
lstBxvende.Items.Add(vende[i]);
}
}

private void bttnza_Click(object sender, EventArgs e)


{
lstBxvende.Items.Clear();
Array.Reverse(vende);
for (int i = 0; i < 10; i++)
{
lstBxvende.Items.Add(vende[i]);
}
}

private void bttnquit_Click(object sender, EventArgs e)


{
lstBxvende.Items.Remove(lstBxvende.SelectedItem);

private void bttnbusc_Click(object sender, EventArgs e)


{
string nombre = txtBxnom.Text;
for (int i = 0; i < 10; i++)
{
int index = lstBxvende.FindString(nombre);
if (index!=-1)
{
lstBxvende.SetSelected(index, true);
}
else
{
MessageBox.Show("Nombre no encontrado");
break;
}

29
E-PORTAFOLIO PROGRAMACIÓN II

}
}
}

Aplicación que genera de manera automática una Matriz “A” (5x5) y una Matriz “B”
(5x5), ambas con números aleatorios entre 10 y 90, y crea una función personaliza,
que reciba como parámetros: la matriz “A”, la matriz “B” y el tipo de operación a
realizar (sumar o multiplicar), la función deberá retornar el arreglo resultante y será
mostrado en el DataGridView “Resultado”.

30

Vous aimerez peut-être aussi