Avoid duplicate records in C # in modify

1

I have a function that does not allow me to enter the same data in the same row. at the time of entering a new product if it works I can not enter a product that is already in the database, the problem if I want to change and I only want to change the sale price example can not because it can not be saved with the same name ANY IDEA?

THIS IS MY SAVE BUTTON

 private void btnGuardar_Click(object sender, EventArgs e)
    {
        try
        {
            if (modificar)
            {

                Eproductos editar = new Eproductos();
                bool exist = dgvfiltrarproductos.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["Producto"].Value) == txtnombre.Text);
                bool exist2 = dgvfiltrarproductos.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["CodSAC"].Value) == txtCodSAC.Text);
                //SI EL VALOR NO EXISTE EN LA BASE DE DATOS LO INGRESA  
                if (!exist == true)
                {

                    if (!exist2 == true)
                    {
                        editar.Codproducto = Convert.ToInt32(txtnombre.Tag.ToString());
                        editar.Producto = txtnombre.Text;
                        editar.CodSac = txtCodSAC.Text;
                        editar.Marca.Codmarca = Convert.ToInt32(txtmarca.Text.ToString());
                        editar.Existencia = Convert.ToDecimal(txtexistencia.Text.ToString());
                        editar.Precio = Convert.ToDecimal(txtprecioventa.Text.ToString());
                        editar.Costo = Convert.ToDecimal(txtpreciocompra.Text.ToString());
                        if (rbtnActvivo.Checked == true)
                        {
                            editar.Activo = true;
                        }
                        else
                        {
                            editar.Activo = false;
                        }

                        Nproductos gestion = new Nproductos();
                        gestion.modificar(editar);
                        MessageBox.Show("Se modifico correctamente", "PRODUCTO", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                    else
                    {
                        MessageBox.Show("Este CodSAC ya fue ingresado", "REVISE");
                    }
                }
                //SI EL VALOR EXISTE EN LA BASE DE DATOS NO LO INGRESA
                else
                {                     
                    MessageBox.Show("Este producto ya fue ingresado", "REVISE");
                }
            }
            else
            {
                Eproductos nuevo = new Eproductos();
                //COMPROBAR SI EL REGISTRO YA EXISTE CON UNA CONSULTA "LINQ" RECORRE TODA LA FILA DEL DATAGRID VIEW Y LA COLUMNA ESPECIFICA  .
                bool exist = dgvfiltrarproductos.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["Producto"].Value) == txtnombre.Text);
                bool exist2 = dgvfiltrarproductos.Rows.Cast<DataGridViewRow>().Any(row => Convert.ToString(row.Cells["CodSAC"].Value) == txtCodSAC.Text);
                //SI EL VALOR NO EXISTE EN LA BASE DE DATOS LO INGRESA                
                if (!exist == true)
                {
                    if (!exist2 == true)
                    {
                        nuevo.Producto = txtnombre.Text;
                        nuevo.Marca.Codmarca = Convert.ToInt32(txtmarca.Text.ToString());
                        nuevo.CodSac = txtCodSAC.Text;
                        nuevo.Existencia = Convert.ToDecimal(txtexistencia.Text.ToString());
                        nuevo.Precio = Convert.ToDecimal(txtprecioventa.Text.ToString());
                        nuevo.Costo = Convert.ToDecimal(txtpreciocompra.Text.ToString());
                        if (rbtnActvivo.Checked == true)
                        {
                            nuevo.Activo = true;
                        }
                        else
                        {
                            nuevo.Activo = false;
                        }
                        Nproductos gestion = new Nproductos();
                        gestion.agregar(nuevo);
                        MessageBox.Show("Se guardo correctamente", "PRODUCTO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else
                    {
                        listaproducto.Add(nuevo);
                        MessageBox.Show("Este CodSAC ya fue ingresado", "REVISE");
                    }


                }
                //SI EL VALOR EXISTE EN LA BASE DE DATOS NO LO INGRESA
                else
                {
                    listaproducto.Add(nuevo);
                    MessageBox.Show("Este producto ya fue ingresado", "REVISE");
                }              
            }

            ActualizarLista();
            Limpiar();
            Deshabilitar();
            btnGuardar.Enabled = false;
            btnCancelar.Enabled = false;
            btnModificar.Enabled = false;
            btnBuscarmarca.Enabled = false;
            btnNuevo.Enabled = true;
            modificar = false;
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

    }
    
asked by gelder gomez 31.03.2018 в 02:08
source

1 answer

1

Occasionally I have performed the same operation but with users, and I have been presented with this problem, using Java , the way I solve it, was the following:

Having selected a user to modify, when clicking on the modify button I first do a select to the database, where I get the name of the selected user, if the name is the same as the one in the text box name, lets you modify it, but if it is not passed to a else where it verifies that it does not collide with any other registered user, if this is the case, let it modify it if not.

Here I leave a bit of code of what you said before, so you understand me better:

//Que no se repita, pero que si el que se repite es el mismo, que si lo deje
boolean cumple = false;

String consulta_nombre_usuario = "SELECT Nombre_Usuario"
        + " FROM Usuarios"
        + " WHERE Id_Usuario = " + Id_Usuario;
jClsConexionMetodos CM0 = new jClsConexionMetodos();
String usuario_en_db = CM0.ObtenerValor("Nombre_Usuario", consulta_nombre_usuario);
if (jTxt_NombreUsuario.getText().equals(usuario_en_db))
{
    cumple = true;
} else
{
    //Si no es el mismo, mira si no se repite con ningun otro
    String consulta_usuario_repetido = "SELECT Nombre_Usuario"
            + " FROM Usuarios"
            + " WHERE Nombre_Usuario = '" + jTxt_NombreUsuario.getText() + "'";
    jClsConexionMetodos CM1 = new jClsConexionMetodos();
    String usuario_repetido = CM1.ObtenerValor("Nombre_Usuario", consulta_usuario_repetido);
    if (usuario_repetido.equals(""))
    {
        cumple = true;
    } else
    {
        cumple = false;
    }
}

in the previous case Id_Usuario is the ID of the user that I am modifying ObtenerValor is a method that works as follows:

First parameter: is the column of the query that I want you to get

Second parameter: is the query that will execute

I use a .equals("") because if you do not find anything the ObtenerValor method, it is done so that instead of null returns an empty string.

As an aggregate I can say that the variable cumple after the end of the code that in this answer falls in a if , where if true follows the modified process, if it is false falls in a else where you launch an alert where it says that the name is already being used.

I hope this can give you some idea of how to solve your problem, it is practically like the one I propose here but applied to users, in your case it would be with products.

    
answered by 31.03.2018 / 04:30
source