I have this code and when I try to modify by pressing the Modify button , it tells me that I must declare the scalar variable @Cedula , which by the way is the one I use as an identifier to make the modifications.
private void BtnModificar_Click(object sender, EventArgs e)
{
Conexion.Conectar();
if (txtCedula.Text != "")
{
string sexo = string.Empty;
if (rdHombre.Checked)
{
sexo = "Hombre";
}
else if (rdMujer.Checked)
{
sexo = "Mujer";
}
string actualizar = "UPDATE DatosEstudiantes SET Nombre=@Nombre, Apellidos=@Apellidos, Carrera=@Carrera, LugarNacimiento=@LugarNacimiento, FechaNacimiento=@FechaNacimiento, Sexo=@Sexo, Direccion=@Direccion, Telefono=@Telefono, Provincia=@Provincia, LiceoProcede=@LiceoProcede,Foto=@Foto WHERE Cedula=@Cedula";
SqlCommand cmd = new SqlCommand(actualizar, Conexion.Conectar());
cmd.Parameters.AddWithValue("@Nombre", txtNombres.Text);
cmd.Parameters.AddWithValue("@Apellidos", txtApellidos.Text);
cmd.Parameters.AddWithValue("@Carrera", cmbCarrera.Text);
cmd.Parameters.AddWithValue("@LugarNacimiento", txtLugarNacimiento.Text);
cmd.Parameters.AddWithValue("@FechaNacimiento", cmbFechaNacimiento.Text);
cmd.Parameters.AddWithValue("@Sexo", sexo);
/*cmd.Parameters.AddWithValue("@EstadoCivil", .SqlDbType.Date);*/
cmd.Parameters.AddWithValue("@Direccion", txtDireccion.Text);
cmd.Parameters.AddWithValue("@Telefono", txtTelefono.Text);
cmd.Parameters.AddWithValue("@Provincia", cmbProvincia.Text);
cmd.Parameters.AddWithValue("@LiceoProcede", txtLiceoProcede.Text);
cmd.Parameters.AddWithValue("@Foto", pbImagen.Image);
// Asignando el valor de la imagen
// Stream usado como buffer
System.IO.MemoryStream ms = new System.IO.MemoryStream();
// Se guarda la imagen en el buffer
pbImagen.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
// Se extraen los bytes del buffer para asignarlos como valor para el
// parámetro.
cmd.Parameters["@Foto"].Value = ms.GetBuffer();
cmd.ExecuteNonQuery();
cmd.ExecuteNonQuery();
MessageBox.Show("Actualización Exitosa");
}
}
In your code you don't create the connection object and you don't open it.
you should put this
The SqlConnection object is created, which establishes the connection with the database, this connection must receive as a parameter the connection string which stores the connection data, such as the name of the database, server, user and password if it has one, this SqlConnection object is created within the using to guarantee its destruction once the using is exited, later the SqlCommand is created receiving the command to execute as a parameter, which in this case is an update statement and also receives the connection object, the connection is opened and the update is executed.
Here is an example of a connection string "Database=BD;Server=.;user=user;password=key"
Here's how I have it working: