Greetings. I have a class called employee. This class has the 4 basic objectives of a CRUD. I created a constructor that had the basic parameters of the table but not the primary key because it is identity and autoincrements.
It happens that now I need the primary key to delete a value from the table, but when I set the method to create, it asks me to enter the employeeID that is my PK.
{
class Empleados
{
SqlConnection cn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["conexion"].ConnectionString);
public string Nombre { get; set; }
public string Apellido { get; set; }
public string Cedula { get; set; }
public string Direccion { get; set; }
public int Empleado_ID { get; set; }
public Empleados()
{
}
public Empleados(string nombre, string apellido, string cedula, string direccion, int empleadoid)
{
this.Nombre = nombre;
this.Apellido = apellido;
this.Cedula = cedula;
this.Direccion = direccion;
this.Empleado_ID = empleadoid;
}
public bool registrar()
{
string query = "INSERT INTO EMPLEADOS (NOMBRE, APELLIDO, CEDULA, DIRECCION)";
query += " VALUES (@NOMBRE, @APELLIDO, @CEDULA, @DIRECCION)";
try
{
cn.Open();
SqlCommand myCommand = new SqlCommand(query, cn);
myCommand.Parameters.AddWithValue("@NOMBRE", Nombre);
myCommand.Parameters.AddWithValue("@APELLIDO", Apellido);
myCommand.Parameters.AddWithValue("@DIRECCION", Direccion);
myCommand.Parameters.AddWithValue("@CEDULA", Cedula);
myCommand.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Datos insertados correctamente");
}
catch (SqlException p)
{
MessageBox.Show(p.Message);
}
return true;
}
public bool Actualizar()
{
string query = ("UPDATE Empleados set NOMBRE=@NOMBRE, APELLIDO=@APELLIDO, CEDULA=@CEDULA, DIRECCION=@DIRECCION WHERE EMPLEADO_ID=@EMPLEADOID");
try
{
cn.Open();
SqlCommand myCommand = new SqlCommand(query, cn);
myCommand.Parameters.AddWithValue("@NOMBRE", Nombre);
myCommand.Parameters.AddWithValue("@APELLIDO", Apellido);
myCommand.Parameters.AddWithValue("@DIRECCION", Direccion);
myCommand.Parameters.AddWithValue("@CEDULA", Cedula);
myCommand.Parameters.AddWithValue("@EMPLEADOID", Empleado_ID);
myCommand.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Datos actualizados correctamente");
}
catch (SqlException p)
{
MessageBox.Show(p.Message);
}
return true;
}
}
}
This is my view of Create, so you have an idea of how everything is going.
private void btnguardar_Click(object sender, EventArgs e)
{
var Empleados = new Clases.Empleados(txtnombre.Text, txtapellido.Text, txtcedula.Text, txtdireccion.Text);
Empleados.registrar();
}