jueves, 31 de mayo de 2012

Mostrar una variable en un TextBox C#


Para mostrar una variable de un tipo diferente al tipo cadena (string) en un TextBox
Existen varias formas las cuales son explicadas enseguida

//variable de tipo entero llamada numero
int numero = 123;
            //opción 1----------------------------------
            //aquí asignamos al textbox el resultado de
            //convertir a string la variable numero
            textBox1.Text = Convert.ToString(numero);
            //opción 2--------------------------------------
            //aquí va primero la variable con la terminación
            //de la conversión a string
            textBox1.Text = numero.ToString();
            //-----opción 3----------------------------------------
            //algo más tardado sería declarar primero una
            //variable string y convertir la variable de tipo entero
            string mensaje = Convert.ToString(numero);
            //enseguida se muestra en el textbox esta variable
            textBox1.Text = mensaje;

Enseguida se usará una de las opciones anteriores:

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

namespace convertir_a_string
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int numero = 123;
            textBox1.Text = numero.ToString();
        }
    }
}



Llenar combobox con campos concatenados de una base de datos en C#



//este método llena un combobox con datos de una base
// de datos de sql server 2008 uniendo dos campos como uno solo
//la tabla se llama Profesor y se trata de mostrar en el combobox
//el nombre del profesor con su apellido paterno y teniendo como valor real al seleccionar un elemento el ID_Profesor

public void llenarProfesor()
        {
//enlace con la base de datos
            SqlConnection conexion = new SqlConnection();
            conexion.ConnectionString = enlace;
            conect = conexion.ConnectionString;
            //se declara el DataSet
            DataSet ds3 = new DataSet();
//se indica la consulta e sql donde se elige el ID_Profesor
//y se concatenan los campos Nombre y Apellido_P
//en una variable llamada Name_Full
            SqlDataAdapter da3 = new SqlDataAdapter("Select ID_Profesor,(Nombre + \' \' + Apellido_P) as Name_Full FROM Profesor WHERE Eliminado = 'FALSE'",conect);
//se especifica la tabla
            da3.Fill(ds3, "Profesor");
            cbProfesor.DataSource = ds3.Tables[0].DefaultView;
//el valor real será el ID_Profesor
            cbProfesor.ValueMember = "ID_Profesor";
//lo que mostrará sera la variable Name_Full la cual tiene concatenados los campos Nombre y Apellido_P
            cbProfesor.DisplayMember = "Name_Full";
        }

Llena ComboBox con ID y muestra otro campo en C#


            //este método nos llenara un combobox con datos de una
// base de datios de sql server 2008, en este caso se tiene
//una tabla llamda dia donde se almacena el ID_Dia como llave
// primaria y el campo Dia para el nombre del dia, el combobox
// va a mostrar el nombre del dia pero al seleccionar uno de
//ellos en realidad seleccionaremos el ID_Dia

public void llenarDia()
        {

//se realiza la conexión a la base de datos
            SqlConnection conexion = new SqlConnection();
            conexion.ConnectionString = enlace;
            conect = conexion.ConnectionString;
            //se inicia un DataSet
            DataSet dsd = new DataSet();
            //se indica la consulta en sql
            SqlDataAdapter dad = new SqlDataAdapter("SELECT ID_Dia_semana,Dia FROM Dia_de_la_semana",conect);
            //se indica con quu tabla se llena
            dad.Fill(dsd, "Dia_de_la_semana");
            cbDia.DataSource = dsd.Tables[0].DefaultView;
            //indicamos el valor de los miembros
            cbDia.ValueMember = "ID_Dia_semana";
            //se indica el valor a desplegar en el combobox
            cbDia.DisplayMember = "Dia";
           
        }

lunes, 7 de mayo de 2012

Messagebox en C#

Los mensajes en las formas de C#  se pueden mostrar a través de los Messagebox, estos pueden contener información importante para el usuario por ejemplo advertencias, notificaciones,  resultados de operaciones, etc. Se les puede definir tanto botones como íconos. A continuación mostraremos algunos ejemplos con una aplicación que sólo tiene un botón para 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.Windows.Forms;

namespace mesaggebox
{
publicpartialclassForm1 : Form
    {
public Form1()
        {
            InitializeComponent();
        }

privatevoid btn_mensaje_Click(object sender, EventArgs e)
{
//mostrar un mensaje normal
MessageBox.Show("HOLA MUNDO");
        }
    }
}


//Mostrar un mensaje con título
MessageBox.Show("HOLA MUNDO", "Mensaje de muestra");




//Mostrar un mensaje con mas botones que el OK (aceptar)
MessageBox.Show("HOLA MUNDO", "Mensaje de muestra",MessageBoxButtons.YesNoCancel);

 

//Mostrar un mensaje con ícono
MessageBox.Show("HOLA MUNDO", "Mensaje de muestra", MessageBoxButtons.YesNoCancel,MessageBoxIcon.Information);

 



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

namespace mesaggebox
{
publicpartialclassForm1 : Form
    {
public Form1()
        {
            InitializeComponent();
        }

privatevoid btn_mensaje_Click(object sender, EventArgs e)
{
//mostraremos un mensaje normal
//MessageBox.Show("HOLA MUNDO");
//Mostrar un mensaje con título
//MessageBox.Show("HOLA MUNDO", "Mensaje de muestra");
//Mostrar un mensaje con mas botones que el OK (aceptar)
//MessageBox.Show("HOLA MUNDO", "Mensaje de muestra",MessageBoxButtons.YesNoCancel);
//Mostrar un mensaje con ícono
MessageBox.Show("HOLA MUNDO", "Mensaje de muestra", MessageBoxButtons.YesNoCancel,MessageBoxIcon.Information);
        }

privatevoid btn_suma_Click(object sender, EventArgs e)
{
//mostrar una variable en un mensage, en este caso
//el resultado de una suma
//primero calculamos la suma
//declaramos una variable entera para el número 1
//y asignamos su valor convirtiendo a entero
//lo que se encuentra en el textbox txt_num1
int num1 = Convert.ToInt32(txt_num1.Text);
//hacemos lo mismo con el siguiente número
int num2 = Convert.ToInt32(txt_num2.Text);
//se declarar una variable entera para la suma y se realiza la misma
int suma = num1 + num2;
//Mostrar el resultado de la suma
MessageBox.Show("La suma de "+num1+" + "+num2+" es: "+suma+"", "Resultado de la suma", MessageBoxButtons.OK, MessageBoxIcon.Information);

        }
    }
}




sábado, 14 de abril de 2012

Ejemplo de una base de datos en SQL server

Advertencia aun no esta editado totalmente


--se crea la base de datos
create database Tienda on primary
(
--se indica el nombre
name=Tiendasemsix,
--la ruta donde se alojará
filename='D:\Tiendasemsix.mdf',
--su tamaño(espacio en disco) inicial
size=4mb,
--el tamaño máximo que alcanzará
maxsize=10mb,
--y por último el crecimiento gradual
filegrowth=2
)
--ejemplo de una tabla
create table Nombre_de_la_tabla
(
Campo1 tipo_de_dato,--va una coma al final de cada delcración de un campo
Campo2 tipo_de_dato,
Campo3 tipo_de_dato--la línea del campo final no lleva coma
)

--creamos las tablas
--explicaremos una de ellas
--se crea la tabla
create table Cliente
(
--declaramos una llave primaria(primary key) de tipo entero(int),
-- la cual será autoincrementable(crece gradualmente en uno),
--al ser llave primaria no admite valores nulos pero dejamos
-- la instriccion "not null" como ejemplo
ID_Cliente int primary key identity(1,1) not null,
--una clave para el cliente de tipo varchar y de tamaño 50
Clave_Cliente varchar(50)not null,
Nombre varchar(50) not null,
RFC varchar(10) not null,
--un campo llamado saldo de tipo money, el ultimo campo no lleva como al final
Saldo money not null
)

create table Producto
(
ID_Producto int primary key identity(1,1) not null,
Clave_Producto varchar(50) not null,
Descripcion varchar(100) not null,
Costo_Unitario money not null,
Existencia int not null
)

create table Venta
(
ID_Venta int primary key identity(1,1) not null,
--esta es una llave foránea la cual hace referencia a otra tabla
ID_Cliente int not null foreign key(ID_Cliente)references Cliente(ID_Cliente),
ID_Producto int not null foreign key(ID_Producto)references Producto(ID_Producto),
No_Factura int not null,
Cantidad int not null,
Fecha date not null,
Total money not null,
Saldo money not null,
--este es un campo llamado Cancelado de tipo bit
--el cual tiene como valor definido false, también puede ser 0
Cancelado bit default('false')not null,
Tipo_Vta varchar(10)
)

Create table Corte_Caja
(
Fecha date not null,
Total money not null
)

Create table Pago
(
No_Factura int not null,
Monto money not null,
Fecha date not null,
No_Pago int not null,
Saldo_Anterior money ,
Saldo_Nuevo money
)

create table Devolucion
(
No_Factura int not null,
Fecha date not null
)

create procedure Nombre_del_procedimiento
(
--campos que recibe, inician con un @
@Campo1 tipo_de_dato,
@Campo2 tipo_de_dato,
@Campo3 tipo_de_dato--sin coma al final de la última línea
)
as
--inicio del procedimiento
begin
--cuerpo del procedimiento donde pueden ir uno o
--varios grupos de instrucciones
end
--fin del procedimiento
-----------------------------------------------------------VENTA
create procedure Realiza_Vta
(
      @Clave_Cliente varchar(50),
      @Clave_Producto varchar(50),
      @No_Factura int,
      @Cantidad int,
      @Tipo_Vta varchar(10)
)
AS
Begin
      declare @Total money
      if Exists(select *from Cliente where Clave_Cliente=@Clave_Cliente)
            begin
            if Exists(select *from Producto where Clave_Producto=@Clave_Producto)
                  begin
                        if (select Existencia from Producto Where Clave_Producto=@Clave_Producto)>=@Cantidad
                             begin
                              Begin transaction
                                   set @Total=(@Cantidad*(select Costo_Unitario from Producto where ID_Producto=(select ID_Producto from Producto where Clave_Producto=@Clave_Producto)))
                                   Insert into Venta(ID_Cliente,ID_Producto,No_Factura,Cantidad,Fecha,Total,Saldo,Tipo_Vta)values((select ID_Cliente from Cliente where Clave_Cliente=@Clave_Cliente),(select ID_Producto from Producto where Clave_Producto=@Clave_Producto),@No_Factura,@Cantidad,Getdate(),@Total,@Total,@Tipo_Vta)
                                   if @@ERROR>0
                                   goto error 
                             Commit transaction
                             end
                        else
                             begin
                                   goto errorc
                             end  
                  end
            else
                  begin
                        goto errorb
                  end
            end
      else
            begin
                  goto errora
            end
fin1:
goto fin2              
error:
rollback transaction
print 'Ha ocurrido un error'
goto fin2
errora:
print 'No existe el cliente'
goto fin2
errorb:
print 'No existe el producto'
goto fin2
errorc:
print 'Cantidad de productos insuficientes para vender'
fin2:
End
-----------------------------------------------------------------------------------venta editado--------------------

create procedure Realiza_Vta
(
      @Clave_Cliente varchar(50),
      @Clave_Producto varchar(50),
      @No_Factura int,
      @Cantidad int,
      @Tipo_Vta varchar(10)
)
AS
Begin
      declare @Total money
      if Exists(select *from Cliente where Clave_Cliente=@Clave_Cliente)
            begin
            if Exists(select *from Producto where Clave_Producto=@Clave_Producto)
                  begin
                        if (select Existencia from Producto Where Clave_Producto=@Clave_Producto)>=@Cantidad
                             begin
                             Begin transaction
                                   set @Total=(@Cantidad*(select Costo_Unitario from Producto where ID_Producto=(select ID_Producto from Producto where Clave_Producto=@Clave_Producto)))
                                   Insert into Venta(ID_Cliente,ID_Producto,No_Factura,Cantidad,Fecha,Total,Saldo,Tipo_Vta)values((select ID_Cliente from Cliente where Clave_Cliente=@Clave_Cliente),(select ID_Producto from Producto where Clave_Producto=@Clave_Producto),@No_Factura,@Cantidad,Getdate(),@Total,@Total,@Tipo_Vta)
                                   if @@ERROR>0
                                   goto error 
                                   Commit transaction
                             end
                        else
                             begin
                                   goto errorc
                             end  
                  end
            else
                  begin
                        goto errorb
                  end
            end
      else
            begin
                  goto errora
            end
fin1:
return     
error:
rollback transaction
print 'Ha ocurrido un error'
goto fin2
errora:
print 'No existe el cliente'
goto fin2
errorb:
print 'No existe el produto'
goto fin2
errorc:
print 'Productos insuficientes para realizar la venta'
fin2:
End

--------------------------------------------------------------------------------------------------------------------
create trigger Nombre_del_trigger
on Tabla_con_la_cual_se_activa after|before|for insert|update|delete
as
--inicio del trigger
begin
--cuerpo del grupo de instrucciones
end
--final


create trigger Inserta_Vta_Trg
on Venta After insert
As
Begin
Begin Transaction
      if (select Tipo_Vta from inserted)='CONTADO'
            begin
                  if Exists(select *from Corte_Caja where Fecha=(select Fecha From inserted))
                        begin
                        update Corte_Caja set Total=Total+(select Saldo from inserted) where Fecha=(select Fecha From inserted)
     
                        if @@ERROR>0
                        goto error
                        end
                  else
                        begin
                        Insert into Corte_Caja(Fecha,Total)values(Getdate(),(select Saldo from inserted))
                        if @@ERROR>0
                        goto error
                        end
            end
      else
            begin
            update Cliente set Saldo=Saldo+(select Saldo from inserted) where ID_Cliente=(select ID_Cliente from Inserted)
     
            if @@ERROR>0
            goto error
            end
            update Producto set Existencia=Existencia-(Select Cantidad from inserted) where ID_Producto=(select ID_Producto from inserted)
     
      if @@ERROR>0
            goto error
      Commit Transaction     
      fin1:
goto fin2  
error:
Rollback Transaction
print 'ha ocurrido un error'

End
-------------------------------------------------------PAGO------------------------------------------------------
create procedure Realiza_Pago
(
      @No_Factura int,
      @Monto money,
      @Comprobacion int output
)
as
Begin
      Begin Transaction
      set @Comprobacion=0
      insert into Pago(No_Factura,Monto,Fecha,No_Pago)values(@No_Factura,@Monto,getdate(),((select count(No_Pago) from Pago where No_Factura=@No_Factura)+1))
      if @@ERROR>0
                        goto error
      Commit Transaction
      noerror:
      set @Comprobacion=1
      goto fin
      error:
      Rollback Transaction
      set @Comprobacion=0
      fin:
End



create trigger Inserta_Pago_Trg
on Pago after insert
as
Begin
      Begin Transaction
      declare @Saldo_Anterior money,@Saldo_Nuevo money
      if (select No_Pago from inserted)>1
            begin
            set @Saldo_Anterior=(select Saldo_Nuevo from Pago where No_Factura=(select No_Factura from inserted) and No_Pago=((select No_Pago from inserted)-1))
            end
      else
            begin
            set @Saldo_Anterior=(select Saldo from Venta Where No_Factura=(select No_Factura from inserted))
            end

set @Saldo_Nuevo=@saldo_Anterior-(select Monto from inserted)
update Pago set Saldo_Anterior=@Saldo_Anterior,Saldo_Nuevo=@Saldo_Nuevo where No_Pago=(select No_Pago from inserted)
if @@ERROR>0
                  goto error 
      update Cliente set Saldo=Saldo-(select Monto from inserted)where ID_Cliente=(Select ID_Cliente from Venta where No_Factura=(select No_Factura from inserted))
      if @@ERROR>0
                        goto error
      update Venta set Saldo =@Saldo_Nuevo where No_Factura=(select No_Factura from inserted)
      if @@ERROR>0
                        goto error
      if exists(select Total from Corte_Caja where Fecha=(select Fecha from Inserted))
            begin
            update Corte_Caja set Total=Total+(select Monto from inserted) where Fecha=(select Fecha from inserted)
            if @@ERROR>0
                        goto error
            end
      else
            begin
            insert into Corte_Caja(Fecha,Total)values(getdate(),(select Monto from inserted))
            if @@ERROR>0
                        goto error
            end
      Commit Transaction          
noerror:
goto fin         
error:
Rollback Transaction
print 'se ha producido un error'        
fin:
End
---------------------------------------------------------devolucion-----------------------------------
create procedure Realiza_Devolucion
(
@No_Factura int,
@Comprobacion int output
)
as
begin
Begin Transaction
set @Comprobacion=0
insert into Devolucion(No_Factura,Fecha)values(@No_Factura,getdate())
if @@error>0
goto error
Commit Transaction
noerror:
set @Comprobacion=1
goto fin
error:
Rollback Transaction
set @Comprobacion=0
fin:
end

create trigger Inserta_Devolucion_Trg
On Devolucion after insert
as
begin
      Begin Transaction
      update Producto set Existencia=Existencia+(select Cantidad from Venta where No_Factura=(select No_Factura from inserted)) where ID_Producto=(select ID_Producto from Venta where No_Factura=(select No_Factura from inserted))
      if @@error>0
            goto error
      if (select Tipo_Vta from Venta where No_Factura=(select No_Factura from inserted))='CONTADO'
            begin
            if Exists(select *from Corte_Caja where Fecha=(select Fecha from inserted))
                  begin
                  update Corte_Caja set Total=Total-(select Saldo from Venta where No_Factura=(select No_Factura from inserted))where Fecha=(select Fecha from inserted)
                  if @@ERROR>0
                  goto error
                  end
            else
                  begin
                  Insert into Corte_Caja(Fecha,Total)values(Getdate(),((select Saldo from Venta where No_Factura=(select No_Factura from inserted))*(-1)))
                  if @@ERROR>0
                  goto error
                  end
            end
      else
            begin
                  update Cliente set Saldo=Saldo-(select Saldo from Venta where No_Factura=(select No_Factura from inserted)) where ID_Cliente=(select ID_Cliente from Venta where No_Factura=(select No_Factura from inserted))
                  if @@error>0
                        goto error
            end  
update Venta Set Cancelado='true' where No_Factura=(select No_Factura from inserted)
if @@error>0
goto error
Commit Transaction
noerror:
goto fin   
error:
Rollback Transaction
print 'Ha ocurrido un error'
fin:
end