Sei sulla pagina 1di 10

////(Registrar, Actualizar) y hacemos que el mantenimiento del c�digo se realice a

un mismo formulario.

public ActionResult Crud(int id = 0)


{
ViewBag.Cursos = curso.Todo();
return View(
id > 0 ? alumno.Obtener(id)
: alumno
);
}

-----------------------------------------------------------------------------------
------

////Nuevo Registro,Actualizaci�n.
public List<Curso> Todo()
{
var cursos = new List<Curso>();
try
{
using (var context = new TestContext())
{
cursos = context.Curso.ToList();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}

return cursos;
}
-----------------------------------------------------------------------------------
------------------------
///La vista de nuestro formulario
Hemos usado los HTML Helper para crear los textbox y dem�s controles que tengamos.

@model Model.Alumno
@{
ViewBag.Title = (Model.id > 0 ? Model.Nombre + " " + Model.Apellido : "Nuevo
registro");
List<Model.Curso> cursos = ViewBag.Cursos;
}

<ol class="breadcrumb">
<li><a href="~/">Alumnos</a></li>
<li class="active">@(Model.id > 0 ? Model.Nombre + " " + Model.Apellido : "Nuevo
registro")</li>
</ol>

@using (Html.BeginForm("Guardar", "Home", FormMethod.Post, new { id = "frm-


alumno" }))
{
@Html.HiddenFor( x => x.id )
<div class="panel panel-default">
<div class="panel-heading">Informaci�n personal</div>
<div class="panel-body">
<div class="form-group">
@Html.LabelFor(x => x.Nombre)
@Html.TextBoxFor(x => x.Nombre, new { @class = "form-control" })
</div>
<div class="form-group">
@Html.LabelFor( x => x.Apellido)
@Html.TextBoxFor(x => x.Apellido, new { @class = "form-control" })
</div>
</div>
</div>

<div class="panel panel-default">


<div class="panel-heading">Asignaturas</div>
<div class="panel-body">
<ul class="list-group">
@foreach (var c in cursos)
{
var tomado = false;
foreach (var c2 in Model.Cursos)
{
if (c.id == c2.id)
{
tomado = true;
break;
}
}
<li class="list-group-item">
<label><input type="checkbox" @(tomado ? "checked" : "")
name="cursos" value="@c.id" /> @c.Nombre</label>
</li>
}
</ul>
</div>
</div>

<div class="text-right">
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
}
-----------------------------------------------------------------------------------
-----------------
//La acci�n para registrar/actualizar un alumno

public ActionResult Guardar(Alumno model, int[] cursos = null)


{
if (cursos != null)
{
foreach (var c in cursos)
model.Cursos.Add(new Curso { id = c });
}

model.Guardar();

return Redirect("~/home/crud/" + model.id);


}
----------------------------------------------------------------------------
///Implementando el m�todo Guardar en la clase Alumno
public void Guardar()
{
try
{
using (var context = new TestContext())
{
if (this.id == 0)
{
context.Entry(this).State = EntityState.Added;
}
else
{
context.Database.ExecuteSqlCommand(
"DELETE FROM AlumnoCurso WHERE Alumno_id = @id",
new SqlParameter("id", this.id)
);

var cursoBK = this.Cursos;

this.Cursos = null;
context.Entry(this).State = EntityState.Modified;
this.Cursos = cursoBK;
}

foreach (var c in this.Cursos)


context.Entry(c).State = EntityState.Unchanged;

context.SaveChanges();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
}
-----------------------------------------------------------------------------------
---
////nuevo registro.
if (this.id == 0)
{
context.Entry(this).State = EntityState.Added;
}
else
{
/* L�gica para actualizar */
}

foreach (var c in this.Cursos)


context.Entry(c).State = EntityState.Unchanged;

context.SaveChanges();
--------------------------------------------------------------------------
///Ahora vamos analizar el c�digo para cuando al condici�n se da para un registro
que ya existe y queremos actualizarlo.

if (this.id == 0)
{
/* logica para registro nuevo */
}
else
{
context.Database.ExecuteSqlCommand(
"DELETE FROM AlumnoCurso WHERE Alumno_id = @id",
new SqlParameter("id", this.id)
);

var cursoBK = this.Cursos;

this.Cursos = null;
context.Entry(this).State = EntityState.Modified;
this.Cursos = cursoBK;
}

foreach (var c in this.Cursos)


context.Entry(c).State = EntityState.Unchanged;

context.SaveChanges();

ESTE ES OTRO CODIGO


===================================================================================
=========================
//Variables
string lbl = "";
string path = "";
//NombreApp ser� el identificador en el registro

string nombreApp = "";


//Evento load del formulario

private void Formulario_Load(object sender, EventArgs e)


{
lbl = Path.GetFileName(System.Reflection.Assembly.GetExecutingAssembly().
GetName().CodeBase);
path = Path.GetDirectoryName(System.Reflection.Assembly.
GetExecutingAssembly().GetName().CodeBase).Remove(0, 6) + "\\" + lbl;
nombreApp = "MiAplicacion";
}
Por consiguiente en el bot�n btnInicio realizaremos el siguiente c�digo :
// Resgistrar� en Inicio del registro la aplicaci�n indicada
// Devuelve True si todo fue bien, False en caso contrario
// Guardar la clave en el registro
// HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
try
{
RegistryKey runK = Registry.LocalMachine.OpenSubKey
(@"Software\Microsoft\Windows\CurrentVersion\Run", true);
// a�adirlo al registro
// Si el path contiene espacios se deber�a incluir entre comillas dobles
if (nombreApp.StartsWith("\"") == false && nombreApp.IndexOf(" ") > -1)
{
nombreApp = "\"" + nombreApp + "\"";
}
runK.SetValue(path, nombreApp);
return true;
}
catch (Exception ex)
{
Console.WriteLine("ERROR al guardar en el registro.{0}Seguramente no
tienes privilegios suficientes.{0}{1}{0}---xxx---{2}", '\n',
ex.Message, ex.StackTrace);
return false;
}

Y finalmente en el boton btnNoInicio el siguiente codigo :


// Quitar� de Inicio la aplicaci�n indicada
// Devuelve True si todo fue bien, False en caso contrario
// Si la aplicaci�n no estaba en Inicio, devuelve True salvo que se produzca
un error
try
{
RegistryKey runK = Registry.LocalMachine.OpenSubKey(@"Software\Microsoft
\Windows\CurrentVersion\Run", true);
// quitar la clave indicada del registo
runK.DeleteValue(path, false);
return true;
}
catch (Exception ex)
{
Console.WriteLine("ERROR al eliminar la clave del registro.{0}
Seguramente no tienes privilegios suficientes.{0}{1}{0}---xxx---{2}",
'\n',
ex.Message, ex.StackTrace);
return false;
}

==============================================================================
________________________________________________________________________________
///ESTE OTRA CODIGO DE C#
using System;
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.Data.SqlClient;

namespace crud
{
public partial class frmProductos : Form
{
// Realizo la Conexi�n a la Base de Datos
string connectionString =
@"Server=.\sqlexpress;Database=productos;Trusted_Connection=True;";
bool nuevo;

public frmProductos()
{
InitializeComponent();
}
// Cargo el Formulario y su estado para cada elemento.
private void frmProductos_Load(object sender, EventArgs e)
{
tsbNuevo.Enabled = true;
tsbGuardar.Enabled = false;
tsbCancelar.Enabled = false;
tsbEliminar.Enabled = false;
tstId.Enabled = true;
tsbBuscar.Enabled = true;
txtNombre.Enabled = false;
txtPrecio.Enabled = false;
}

private void txtId_TextChanged(object sender, EventArgs e)


{

private void tsbNuevo_Click(object sender, EventArgs e)


{
// Cargo el estado para el bot�n Nuevo y los dem�s elementos.
tsbNuevo.Enabled = false;
tsbGuardar.Enabled = true;
tsbCancelar.Enabled = true;
tsbEliminar.Enabled = false;
tstId.Enabled = false;
tsbBuscar.Enabled = false;
txtNombre.Enabled = true;
txtPrecio.Enabled = true;
txtStock.Enabled = true;
txtNombre.Focus();
nuevo = true;
}

private void tsbGuardar_Click(object sender, EventArgs e)


{
// Cuando hago click en el bot�n Nuevo que proceda la inserci�n de un
registro en la Base de Datos.
if (nuevo)
{
string sql = "INSERT INTO POSTRES (NOMBRE, PRECIO, STOCK)"
+ "VALUES ('" + txtNombre.Text + "', '" + txtPrecio.Text
+ "', '" + txtStock.Text + "')";

SqlConnection con = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
int i = cmd.ExecuteNonQuery();
if (i &gt; 0)
MessageBox.Show("Registro ingresado correctamente !");
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.ToString());
}
finally
{
// Cierro la Conexi�n.
con.Close();
}
}
else
{
// Procedo a realizar la actualizaci�n del registro en la Base de
Datos.
string sql = "UPDATE POSTRES SET NOMBRE='" + txtNombre.Text +
"', PRECIO='" + txtPrecio.Text +
"', " + "STOCK='" + txtStock.Text + "'";

SqlConnection con = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
con.Open();
try
{
int i = cmd.ExecuteNonQuery();
if (i &gt; 0)
MessageBox.Show("Registro actualizado correctamente !");
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.ToString());
}
finally
{
// Cierro la Conexi�n.
con.Close();
}
}

// Defino los Estados para los elementos de mi Formulario despu�s de


actualizar el registro.
tsbNuevo.Enabled = true;
tsbGuardar.Enabled = false;
tsbCancelar.Enabled = false;
tsbEliminar.Enabled = false;
tstId.Enabled = true;
tsbBuscar.Enabled = true;
txtNombre.Enabled = false;
txtPrecio.Enabled = false;
txtStock.Enabled = false;
txtId.Text = "";
txtNombre.Text = "";
txtPrecio.Text = "";
txtStock.Text = "";
}

private void tsbCancelar_Click(object sender, EventArgs e)


{
// Defino los Estados para los elementos de mi Formulario cuando hago
click en el bot�n Cancelar.
tsbNuevo.Enabled = true;
tsbGuardar.Enabled = false;
tsbCancelar.Enabled = false;
tsbEliminar.Enabled = false;
tstId.Enabled = true;
tsbBuscar.Enabled = true;
txtNombre.Enabled = false;
txtPrecio.Enabled = false;
txtStock.Enabled = false;
txtId.Text = "";
txtNombre.Text = "";
txtPrecio.Text = "";
txtStock.Text = "";
}

private void tsbEliminar_Click(object sender, EventArgs e)


{
// Si hago click en el bot�n eliminar procedo a eliminar en la Base de
Datos.
string sql = "DELETE FROM POSTRES WHERE ID=" + txtId.Text;

SqlConnection con = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
con.Open();

try
{
int i = cmd.ExecuteNonQuery();
if (i &gt; 0)
MessageBox.Show("Registro eliminado correctamente !");
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.ToString());
}
finally
{
// Cierro la Conexi�n.
con.Close();
}

// Defino los Estados para los elementos de mi Formulario cuando hago


click en el bot�n Eliminar.
tsbNuevo.Enabled = true;
tsbGuardar.Enabled = false;
tsbCancelar.Enabled = false;
tsbEliminar.Enabled = false;
tstId.Enabled = true;
tsbBuscar.Enabled = true;
txtNombre.Enabled = false;
txtPrecio.Enabled = false;
txtStock.Enabled = false;
txtId.Text = "";
txtNombre.Text = "";
txtPrecio.Text = "";
txtStock.Text = "";
}

private void tsbBuscar_Click(object sender, EventArgs e)


{
// Cuando hago click en el bot�n Buscar, procedo a buscar en la Base de
Datos.
string sql = "SELECT * FROM POSTRES WHERE ID=" + tstId.Text;

SqlConnection con = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand(sql, con);
cmd.CommandType = CommandType.Text;
SqlDataReader reader;
con.Open();

try
{
reader = cmd.ExecuteReader();
if (reader.Read())
{
// Defino los Estados para los elementos de mi Formulario
cuando hago click en el bot�n Buscar.
tsbNuevo.Enabled = false;
tsbGuardar.Enabled = true;
tsbCancelar.Enabled = true;
tsbEliminar.Enabled = true;
tstId.Enabled = false;
tsbBuscar.Enabled = false;
txtNombre.Enabled = true;
txtPrecio.Enabled = true;
txtStock.Enabled = true;
txtNombre.Focus();
txtId.Text = reader[0].ToString();
txtNombre.Text = reader[1].ToString();
txtPrecio.Text = reader[2].ToString();
txtStock.Text = reader[3].ToString();
nuevo = false;
}
else
MessageBox.Show("Ningun registro encontrado con el Id ingresado
!");
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex.ToString());
}
finally
{
// Cierro la Conexi�n.
con.Close();
}

tstId.Text = "";

private void toolStrip1_ItemClicked(object sender,


ToolStripItemClickedEventArgs e)
{

private void btnSalir_Click(object sender, EventArgs e)


{
// Cuando hago click en el bot�n Salir cierro el formulario.
this.Close();
}
}
}

Potrebbero piacerti anche