domingo, 27 de marzo de 2022

 

como hacer un crud en c# y Postgresql 2022 (create,read,update,eliminar)

   Hola bienvenidos amigos , nuevamente yo por aquí , En este post haremos un crud en c# con la base de datos en POSTGRESQL14


  1. creacion de base de datos
create database colegio

create table alumnos(

   codigo serial,

                nombres varchar(80),

                direccion varchar(100),

                primary key(codigo)      

)

 

insert into alumnos values('1','cristian patricio izquierdo','lima los olivos')

insert into alumnos values('2','lili rodruguez salas','lima los olivos')

insert into alumnos values('3','Yesenia silva salas','lima los olivos')

 

select*from alumnos

2. Diseño de formulario


3. Programación(codigo)
primeramente agregamos nuestro conector desde nuget como la imagen

una vez agregado empezamos a programar
     //conexion global a poostgresql

   NpgsqlConnection cn=new NpgsqlConnection("Server=localhost;User                                              Id=postgres;Password=admin;Database=Colegio");

       

        //list alumnos

        private void getAlumnos()

        {

            NpgsqlDataAdapter da=new NpgsqlDataAdapter("select*from alumnos",cn);

            DataTable dt = new DataTable();

            da.Fill(dt);

            this.dataGridView1.DataSource = dt;

        } 

//insert alumnos
private void insertAlumnos()

        {

            try

            {

                string a;

                a = "insert into alumnos values('" + txtcodigo.Text + "','" +                             (txtnombres.Text) + "','" + (txtdireccion.Text) + "')";

                NpgsqlCommand cmd = new NpgsqlCommand(a, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro guardado correctamente");

                getAlumnos();

            }

 

            catch (InvalidCastException ex)

            { 

                throw ex; 

            } 

        }

//update alumnos

private void updateAlumnos()

 

        {

            try

            {

                string update;

                update = "update alumnos set nombres ='" + txtnombres.Text + "',direccion ='" + txtdireccion.Text + "' where codigo ='" + txtcodigo.Text + "'";

                NpgsqlCommand cmd = new NpgsqlCommand(update, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro actualizado correctamente");

                getAlumnos();

 

            }

 

            catch (InvalidCastException ex)

 

            {

                 throw ex;

 

            }

 

 

        }

//delete alumnos

 

        private void deleteAlumnos()

 

        { 

            try 

            {

                string delete;

                delete = "delete from  alumnos where codigo ='" + txtcodigo.Text + "'";

                NpgsqlCommand cmd = new NpgsqlCommand(delete, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro Eleminado correctamente");

                getAlumnos();

 

            }

 

            catch (InvalidCastException ex)

            { 

                throw ex;

            }

 

        }


//codigo para pasar datos de grid a sus respectivos textbox para eliminar o actualizar

        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)

        {

            if (e.RowIndex >= 0)

            {

                DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];

                txtcodigo.Text = row.Cells["codigo"].Value.ToString();

                txtnombres+.Text = row.Cells["Nombres"].Value.ToString();

                txtdireccion.Text = row.Cells["Direccion"].Value.ToString();

              

 

            }

        }


Bueno eso seria todo espero ayudarlos.


Share:

domingo, 7 de noviembre de 2021

 

c# y SQLSERVER Consultar una fecha en rangos con datetimepicker.

 hey hola ,yo de nuevo por aquí compartiendo este post de como hacer consultas con rango de fechas.

para este ejercicio primeramente creamos nuestro base de datos con su respectivo tabla.

script para la creacion de bd y tabla.

create database tuto

use tuto

 

--creacion de tablas

 

create table ventas(

id int primary key,

fecha datetime,

totalVentas decimal(10,2)

)

go

 

--creamos nuestro procedimiento almacenado

alter procedure buscar

@fechainicial datetime,

@fechafinal datetime

as

select*from ventas where fecha between @fechainicial and @fechafinal

go

Diseño de nuestro formulario como la siguiente imagen

controles a utilizar son: datagridview, datepicker,label,button


codigo fuente:


//metodo para cargar datos a gridview

private void getVentas()

        {

            SqlDataAdapter da = new SqlDataAdapter("select*from ventas", cn);

            DataTable dt = new DataTable();

            da.Fill(dt);

            this.dataGridView1.DataSource = dt;

        }

//metodo para buscar entre fechas.

 

        private void getVentasFecha()

        {

            SqlDataAdapter da = new SqlDataAdapter("buscar", cn);

            da.SelectCommand.CommandType = CommandType.StoredProcedure;

            da.SelectCommand.Parameters.Add("@fechainicial", SqlDbType.DateTime).Value =                     dateTimePicker1.Text;

            da.SelectCommand.Parameters.Add("@fechafinal", SqlDbType.DateTime).Value =                     dateTimePicker2.Text;

            DataTable dt = new DataTable();

            da.Fill(dt);

            this.dataGridView1.DataSource = dt;

        }

//nota importante llamar los métodos de sus respectivos controles

gracias por estar por aqui ,recuerda dejar sus respectivos comentarios de dudas y sugerencias ,estaremos contestando todo sus mensajes.





Share:

miércoles, 6 de octubre de 2021

 

como hacer un crud en c# y sqlserver 2022 (create,read,update,eliminar)

  Hola  amigos , nuevamente yo por aqui , En este post haremos un crud en c# con la base de datos SQLSERVER.

  1. creacion de base de datos.

create database colegios

go

use colegios

go

create table alumnos

(

id int identity (1,1),

nombres varchar(100),

edad int,

telefono char(9) 

)

--insert

insert into alumnos values('cristian',25,123456789)

insert into alumnos values('Ariana ',24,123456786)

 select*from alumnos

2. Diseño de formulario


2. codigo


using System;

using System.Data;

using System.Windows.Forms;

using System.Data.SqlClient;

namespace crudColegio

{

    public partial class Form1 : Form

    {

        SqlConnection cn = new SqlConnection(@"Data Source=CPIPRODESIGN\SQLEXPRESS;Initial Catalog=colegios;Integrated Security=True");

        public Form1()

        {

            InitializeComponent();

        }

 

        private void Form1_Load(object sender, EventArgs e)

        {

            getAlumnos();

        }

        //listar data

        private void getAlumnos()

        {

            try

            {

                SqlDataAdapter da = new SqlDataAdapter("select*from alumnos ", cn);

                DataTable dt = new DataTable();

                da.Fill(dt);

                this.data.DataSource = dt;

 

            }

            catch (InvalidCastException ex)

            {

                throw ex;

            }

            finally

            {

                cn.Close();

            }

        }

        //insert alumnos

 

        private void inserAlumnos()

        {

            try

            {

                string a;

                a = "insert into alumnos values('" + textBox1.Text + "','" + Convert.ToInt32(textBox2.Text) + "','" + (maskedTextBox1.Text) + "')";

                SqlCommand cmd = new SqlCommand(a, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro guardado correctamente");

                getAlumnos();

            }

            catch (InvalidCastException ex)

            {

                throw ex;

 

            }

        }

        //update alumnos

        private void updateAlumnos()

        {

            try

            {

                string update;

                update = "update alumnos set nombres ='" + textBox1.Text + "',edad ='" + textBox2.Text + "', telefono ='" + maskedTextBox1.Text + "' where id ='" + textBox3.Text + "'";

                SqlCommand cmd = new SqlCommand(update, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro actualizado correctamente");

              getAlumnos();

            }

            catch (InvalidCastException ex)

            {

                throw ex;

 

            }

           

        }

        //delete alumnos

        private void deleteAlumnos()

        {

            try

            {

                string delete;

                delete = "delete from  alumnos where id ='" + textBox3.Text + "'";

               SqlCommand cmd = new SqlCommand(delete, cn);

                cn.Open();

                cmd.ExecuteNonQuery();

                cn.Close();

                MessageBox.Show("Registro Eleminado correctamente");

                getAlumnos();

            }

            catch (InvalidCastException ex)

            {

                throw ex;

 

            }

 

        }

 

        private void bunifuFlatButton1_Click(object sender, EventArgs e)

        {

            inserAlumnos();

        }

 

        private void bunifuFlatButton2_Click(object sender, EventArgs e)

        {

            updateAlumnos();

        }

 

        private void bunifuFlatButton3_Click(object sender, EventArgs e)

        {

            deleteAlumnos();

        }

    }

}





eso seria todo gracias.

dudas y sugerencias escribenos en los comentarios

link del proyecto



    


Share: