Codigos utiles para programadores en c# (dgv,mdi,forms,timer,etc)

Rampage94

Lanero Novato
25 May 2013
3
FORM LOGIN TABLAS: CONTEO(id,nombre,segundos) LOGIN(usuario,clave) NOTAS(n1,n2,n3,nf) PERSONA (rut,nombre,fecha_nac)

public partial class Form1 : Form
{
SqlConnection cn;
SqlCommand query;
SqlDataReader dr;
int segundos = 30,intentos=3;
public Form1()
{
try
{
InitializeComponent();
cn = new SqlConnection();
cn.ConnectionString = ("Data Source=Francisco-HP;Initial Catalog=BDSistema;Integrated Security=True;Pooling=False");
cn.Open();
}
catch (Exception ex)
{
MessageBox.Show("problemas en la conexion"+ex.Message);
}
query = new SqlCommand("Select * from login", cn);

}

private void Form1_Load(object sender, EventArgs e)
{
timer1.Enabled = true;


}

private void button1_Click(object sender, EventArgs e)
{
intentos--;
try
{
dr = query.ExecuteReader();
}
catch (Exception ex)
{
MessageBox.Show("Error en la query"+ ex.Message);
}

while (dr.Read())
{
if (textnom.Text == dr.GetString(0) && textpass.Text == dr.GetString(1))
{
mdi nuevo = new mdi();
timer1.Enabled = false;
nuevo.ShowDialog();


}
}
lblintento.Text = "Te queda " + intentos + " intentos";
if (intentos == 0)
{
MessageBox.Show("no quedan intentos");
Application.Exit();
}
dr.Close();

}

private void timer1_Tick(object sender, EventArgs e)
{
if (segundos < 1)
{
timer1.Enabled = false;
MessageBox.Show("se acabo su tiempo");
Application.Exit();
}
segundos--;
}
}
}

------------------------------------------------------------------------------------
MDI LLAMANDO A OTROS FORMULARIOS

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

private void insertarToolStripMenuItem_Click(object sender, EventArgs e)
{
insertar notas = new insertar();
notas.MdiParent = this;
notas.Show();
}

private void conteoToolStripMenuItem_Click(object sender, EventArgs e)
{
conteo cont = new conteo();
cont.MdiParent = this;
cont.Show();
}

private void personaToolStripMenuItem_Click(object sender, EventArgs e)
{
persona per = new persona();
per.MdiParent = this;
per.Show();
}

}
}
-----------------------------------------------------------------------------
FORM INSERTAR NOTAS

public partial class InsertarNotas : Form
{
SqlConnection cn;
public InsertarNotas()
{
InitializeComponent();
}

private void InsertarNotas_Load(object sender, EventArgs e)
{
try
{
cn = new SqlConnection();
cn.ConnectionString = "Data Source=Francisco-HP;Initial Catalog=BDSistema;Integrated Security=True;Pooling=False";
cn.Open();
MessageBox.Show("Conexion establecida");
}
catch (SqlException ex)
{
MessageBox.Show("Error SQL : " + ex.Message);

}
catch (Exception ex)
{
MessageBox.Show("Error SQL : " + ex.Message);

}
}

private void btnCalcular_Click(object sender, EventArgs e)
{
SqlCommand com;


float n1 = float.Parse(txtNota1.Text);
float n2 = float.Parse(txtNota2.Text);
float n3 = float.Parse(txtNota3.Text);


int p1 = int.Parse(txtPorcentaje1.Text);
int p2 = int.Parse(txtPorcentaje2.Text);
int p3 = int.Parse(txtPorcentaje3.Text);

float nf1 =(n1 * p1) / 100;
float nf2 =(n2 * p2) / 100;
float nf3 =(n3 * p3) / 100;

int nff =(int)(nf1 + nf2 + nf3);

com = new SqlCommand("INSERT INTO notas VALUES('"+n1+"','"+n2+"','"+n3+"','"+nff+"')", cn);
com.ExecuteNonQuery();

lblNF.Text = nff.ToString();

}
}
}
--------------------------------------------------------------------------
FORM CONTEO

public partial class conteo : Form
{


SqlConnection cn;
SqlCommand query;
SqlDataReader dr;
DataTable dt= new DataTable();
int cont = 0;


public conteo(){

InitializeComponent();
cn=new SqlConnection();
cn.ConnectionString = ("Data Source=Francisco-HP;Initial Catalog=BDSistema;Integrated Security=True;Pooling=False");

}

private void conteo_Load(object sender, EventArgs e)
{
try
{
cn.Open();
query = new SqlCommand("select * from conteo",cn);

dr = query.ExecuteReader();

dt.Load(dr, LoadOption.OverwriteChanges);
combo.DataSource = dt;
combo.DisplayMember = dt.Columns[1].ToString();
combo.ValueMember = dt.Columns[2].ToString();

}
catch (Exception ex)
{
MessageBox.Show("Error conexion" + ex.Message);

}

}

private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;

}

private void timer1_Tick(object sender, EventArgs e)
{
lblcont.Text = cont.ToString();

if (cont <= int.Parse(combo.SelectedValue.ToString()))
{

lblcont.Text = cont.ToString();

cont++;
}
}
}
}
----------------------------------------------------------------------
FORM PERSONA

public partial class persona : Form
{
SqlConnection cn;
SqlCommand query;
SqlDataReader dr;
DataTable dt=new DataTable();
public persona()
{
try
{
InitializeComponent();
cn = new SqlConnection();
cn.ConnectionString = ("Data Source=Francisco-HP;Initial Catalog=BDSistema;Integrated Security=True;Pooling=False");
cn.Open();
}
catch (Exception ex)
{
MessageBox.Show("error en conexion " + ex.Message);
}

}

private void persona_Load(object sender, EventArgs e)
{
try
{
query = new SqlCommand("select * from persona",cn);

dr = query.ExecuteReader();
dt.Load(dr, LoadOption.OverwriteChanges);
dataGridView1.DataSource = dt;
}
catch (Exception ex)
{
MessageBox.Show("problema con la query " + ex.Message);
}
}

private void button1_Click(object sender, EventArgs e)
{
String rut = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
String nombre = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString();
String fecha_nac = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value.ToString();
DateTime fecha2 = DateTime.Parse(fecha_nac);
try
{
query = new SqlCommand("insert into persona(rut,nombre,fecha_nac) values('" + rut + "','" + nombre + "',@fecha2)", cn);
query.Parameters.Add(new SqlParameter("@fecha2", fecha2));
if (query.ExecuteNonQuery() > 0)
{
MessageBox.Show("se logro la insercion");
}
}catch(Exception Ex){
MessageBox.Show("error query fecha " + Ex.Message);
}
}

private void button2_Click(object sender, EventArgs e)
{
String rut = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
try
{



query = new SqlCommand("delete from persona where rut="+rut+"", cn);

if (query.ExecuteNonQuery() > 0)
{
MessageBox.Show("se logro el borrado");
}
}
catch (Exception Ex)
{
MessageBox.Show("error query fecha " + Ex.Message);
}
}

private void button3_Click(object sender, EventArgs e)
{
String rut = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
String nombre = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString();
String fecha_nac = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value.ToString();
DateTime fecha2 = DateTime.Parse(fecha_nac);
try
{ query = new SqlCommand("update persona set nombre='"+nombre+"',fecha_nac=@fecha3 where rut=" + rut + "", cn);
query.Parameters.Add(new SqlParameter("@fecha3", fecha2));

if (query.ExecuteNonQuery() > 0)
{
MessageBox.Show("se logro la modificacion");
}
}
catch (Exception Ex)
{
MessageBox.Show("error query fecha " + Ex.Message);
}

}
}
}
----------------------------------------------------------------------------
FORM NACIONES PARA INSERTAR,ELIMINAR Y ACTUALIZAR CON DGV (TABLAS: CONTINENTE(cod_c,nombre), PAIS(nombre,cod,cod_c)

public partial class Form1 : Form
{
SqlConnection con;
Data obj;
public Form1()
{


InitializeComponent();
obj = new Data();
con = obj.conectar();
try
{
con.Open();
MessageBox.Show("Conectado Satisfactoriamente");

}
catch (SqlException ex)
{
MessageBox.Show("ERROR SQL: " + ex);
}

catch (Exception exception)
{
MessageBox.Show("ERROR SQL: " + exception);
}
}

private void Form1_Load(object sender, EventArgs e)
{
obj.CBContinente();
DataTable valores = obj.CBContinente();
cbDatos.DataSource = valores;
cbDatos.DisplayMember = valores.Columns[1].ToString();
cbDatos.ValueMember = valores.Columns[0].ToString();


}

private void btnBuscar_Click(object sender, EventArgs e)
{
String valor = cbDatos.SelectedValue.ToString();
int valor2 = int.Parse(valor);
obj.DGVPais(valor2);
DataTable valores2 = obj.DGVPais(valor2);
cbDatos.DataSource = valores2;
dataGridView1.DataSource = valores2;
}

private void btnModificar_Click(object sender, EventArgs e)
{
String cod;
String nom;
DialogResult respuesta = new DialogResult();

if (!dataGridView1.CurrentRow.Selected)
{
cod = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString();
nom = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
respuesta = MessageBox.Show("Desea Actualizar", "Actualización", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (respuesta == DialogResult.Yes)
{
obj.actualizarPais(cod, nom);
}
}
}

private void btnIngresar_Click(object sender, EventArgs e)
{
String cod;
String nom;
String cod2;
DialogResult respuesta = new DialogResult();

if (!dataGridView1.CurrentRow.Selected)
{
cod = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString();
cod2= dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[2].Value.ToString();
nom = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
respuesta = MessageBox.Show("Desea Actualizar", "Actualización", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (respuesta == DialogResult.Yes)
{
obj.ingresarPais(cod, nom, cod2);

}
}

}

private void btnEliminar_Click(object sender, EventArgs e)
{
String nom;
DialogResult respuesta = new DialogResult();

if (!dataGridView1.CurrentRow.Selected)
{
nom = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
respuesta = MessageBox.Show("Desea Actualizar", "Actualización", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (respuesta == DialogResult.Yes)
{
obj.eliminarPais(nom);

}
}

}

}
}

----------------------------------------------------------------------
CLASE DATA

class Data
{
public SqlConnection cn;
private DataTable dt;
private SqlCommand com;
public SqlDataReader dr;



public SqlConnection conectar()
{
cn = new SqlConnection();
cn.ConnectionString = "Data Source=Francisco-HP;Initial Catalog=BDNaciones;Integrated Security=True;Pooling=False";
return cn;
}

public DataTable CBContinente()
{
dt = new DataTable();
com = new SqlCommand("SELECT * FROM continente", cn);
dr = com.ExecuteReader();
dt.Load(dr, LoadOption.OverwriteChanges);

return dt;


}

public DataTable DGVPais(int cont)
{

dt = new DataTable();
com = new SqlCommand("SELECT * FROM pais where cod_c =" + cont, cn);
dr = com.ExecuteReader();
dt.Load(dr, LoadOption.OverwriteChanges);

return dt;

}

public void actualizarPais(String cod, String nom)
{
com = new SqlCommand("UPDATE pais set nombre ='" + nom + "' WHERE cod = '" + int.Parse(cod) + "'", cn);

if (com.ExecuteNonQuery() < 1)
{
Console.WriteLine("error");
}
}

public void ingresarPais(String cod, String nom ,String cod2)
{

com = new SqlCommand("INSERT INTO pais (nombre,cod,cod_c) Values ('" + nom + "', '" + int.Parse(cod) + "', '" + int.Parse(cod2) + "')", cn);

if (com.ExecuteNonQuery() < 1)
{
Console.WriteLine("error");
}
}

public void eliminarPais(String nom)
{

com = new SqlCommand("DELETE FROM pais WHERE nombre = '" + nom + "' ", cn);

if (com.ExecuteNonQuery() < 1)
{
Console.WriteLine("error");
}

}
}
}
-------------------------------------------------------------------------------
FORM PAISES INGRESAR,ELIMINAR,ACTUALIZAR SIN DGV (TABLAS: PAIS:codigo y nombre)

public partial class Form1 : Form
{

SqlConnection cn;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
try
{
cn = new SqlConnection();
cn.ConnectionString = "Data Source=Francisco-HP;Initial Catalog=BDPais;Integrated Security=True;Pooling=False";
cn.Open();
MessageBox.Show("Conexion establecida");
}
catch (SqlException ex)
{
MessageBox.Show("Error SQL : " + ex.Message);

}
catch (Exception ex)
{
MessageBox.Show("Error SQL : " + ex.Message);

}
}

private void btnIngresar_Click(object sender, EventArgs e)
{
SqlCommand comando;
comando = new SqlCommand("INSERT INTO pais (id,nombre) Values ('" + int.Parse(txtCodigo.Text) + "', '" + txtNombre.Text + "')", cn);
if (comando.ExecuteNonQuery() > 0)
{
label3.Text = "Ingreso Satisfactorio";
txtCodigo.Clear();
txtNombre.Clear();
txtCodigo.Focus();
}
}

private void btnBuscar_Click(object sender, EventArgs e)
{
SqlCommand comando;
comando = new SqlCommand("SELECT * FROM pais WHERE id ='" + int.Parse(txtBuscar.Text) + "'", cn);
SqlDataReader dr;
dr = comando.ExecuteReader();
if (dr.Read())
{
lblNombre.Text = dr.GetSqlString(1).ToString();
comando.Dispose();
dr.Dispose();
dr.Close();

}
}

private void btnEliminar_Click(object sender, EventArgs e)
{
SqlCommand comando;
comando = new SqlCommand("DELETE FROM pais WHERE nombre ='" + txtEliminar.Text + "'", cn);
if (comando.ExecuteNonQuery() > 0)
{
label6.Text = "Pais Eliminado del Mapa Señor";
txtCodigo.Clear();
txtNombre.Clear();
txtCodigo.Focus();
}
}
------------------------------------------------------------------------------------
FORM PRODUCTOS TABLAS: PRODUCTO(codigo,nombre)

public partial class Form1 : Form
{
Conexion obj;
public Form1()
{
InitializeComponent();
obj = new Conexion();
}

private void Form1_Load(object sender, EventArgs e)
{
obj.abrirConexion();
DataTable valores = obj.cargarCBproducto();
cbDatos.DataSource = valores;
cbDatos.DisplayMember = valores.Columns[1].ToString();
cbDatos.ValueMember = valores.Columns[0].ToString();
dataGridView1.DataSource = valores;
}

private void btnModificar_Click(object sender, EventArgs e)
{
String cod;
String nom;
DialogResult respuesta = new DialogResult();

if (!dataGridView1.CurrentRow.Selected)
{
cod = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[0].Value.ToString();
nom = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells[1].Value.ToString();
respuesta = MessageBox.Show("Desea Actualizar", "Actualización", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (respuesta == DialogResult.Yes)
{
obj.actualizarProducto(cod, nom);
}
}

}

private void btnMostrar_Click(object sender, EventArgs e)
{

}

}
}
---------------------------------------------------------------------------------
CLASE CONEXION

class Conexion
{
public SqlConnection cn;
public DataTable table;
public SqlCommand query;
public SqlDataReader dr;

public void abrirConexion(){
try
{
cn = new SqlConnection();
cn.ConnectionString = "Data Source=Francisco-HP;Initial Catalog=BDProductos;Integrated Security=True;Pooling=False";
cn.Open();
}
catch(SqlException ex) {

Console.WriteLine("Error" + ex.Message);
}
}//cierre de abrirConexion

public DataTable cargarCBproducto()
{
table = new DataTable();
query = new SqlCommand("SELECT * FROM Producto", cn);
dr = query.ExecuteReader();
table.Load(dr, LoadOption.OverwriteChanges);

return table;

}

public void actualizarProducto(String cod, String nom)
{
query = new SqlCommand("UPDATE Producto set nombre ='" + nom + "' WHERE codigo = '" + int.Parse(cod) + "'", cn);

if (query.ExecuteNonQuery() < 1)
{
Console.WriteLine("error");
}
}

}

}
 

Los últimos temas