Foros del Web » Programación para mayores de 30 ;) » .NET »

Datos duplicados en datagrid vb.net

Estas en el tema de Datos duplicados en datagrid vb.net en el foro de .NET en Foros del Web. HOLA ESTOY TRABAJANDO CON VISUAL STUDIO 2008 Y PASA LO SIGUIENTE: TENGO DOS DATAGRID, EN EL DATAGRID1 CARGO LOS DATOS DE UNA TABLA EN MYSQL ...
  #1 (permalink)  
Antiguo 14/03/2011, 14:02
 
Fecha de Ingreso: marzo-2011
Ubicación: Colombia
Mensajes: 17
Antigüedad: 13 años, 1 mes
Puntos: 0
Información Datos duplicados en datagrid vb.net

HOLA ESTOY TRABAJANDO CON VISUAL STUDIO 2008 Y PASA LO SIGUIENTE:
TENGO DOS DATAGRID, EN EL DATAGRID1 CARGO LOS DATOS DE UNA TABLA EN MYSQL Y EN EL DATAGRID2 AGREGO LOS DATOS SELECCIONADOS DEL DATAGRID1, ÉSTO LO HAGO EN EL EVENTO 'CELLCONTENTDOUBLECLICK'.

PERO LO QUE QUIERO HACER ES QUE EL DATAGRID2 RECIVA SOLAMENTE UN SOLO REGISTRO CON EL MISMO NOMBRE, OSEA, QUE NO LO DUPLIQUE. QUIERO QUE ME APAREZCA UN MENSAJE QUE DIGA: "ÉSTE DATO YA FUÉ AGREGADO"
.

EJEMPLO:
DATAGRID1
CARNE ASADA
PECHUGA A LA PLANCHA
CARNE EN SALSA

DATAGRID2
CARNE ASADA

En éste ejemplo cuando trate de dar dobleclick en el datagrid1 a 'CARNE ASADA', aparézca el mensaje porque el registro ya existe en el datagrid2.

Espero haberme eplicado bien. Gracias!
  #2 (permalink)  
Antiguo 14/03/2011, 14:24
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Buenas tardes Darco1103, te paso un code en c# ya lo conviertes en vb. Saludos!

esto tiene que ir al momento que le das agregar
Código c#:
Ver original
  1. bool existe = false;
  2.             foreach(DataGridViewRow row in datagridview2.Rows){
  3.                 if( Convert.ToString(row.Cells[0].Value).Equals(datagridview1.ActiveRow.Cells[0].Text)){
  4.                     existe = true;
  5.                 }
  6.             }
  7.             if (existe == true)
  8.             {
  9.                 MessageBox.Show("El producto ya fue ingresado", "GRYPHOS");
  10.             }
  11.             else
  12.             {
  13.                 dgCombo.Rows.Add(dgProductos.ActiveRow.Cells[0].Text);
  14.             }
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #3 (permalink)  
Antiguo 14/03/2011, 19:41
Avatar de TECKNOCK  
Fecha de Ingreso: agosto-2010
Mensajes: 80
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: Datos duplicados en datagrid vb.net

Hazlo en el mismo evento CellContentDoubleClick. Supongamos que el nombre de tu columna es Tipo_Carne, recorres todo el DataGrid2 buscando el dato en esa columna y asignas SI o NO a una variable FLAG* para saber si se puede agregar o no.

Aqui te dejo el codigo:


Código vb:
Ver original
  1. Private Sub DataGrid1_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGrid1.CellContentDoubleClick
  2. 'Iniciamos nuestro FLAG en SI
  3. Dim Agregar As String = "SI"
  4. 'Buscamos en todas las FILAS del DataGrid2
  5. For Each FILA As DataGridViewRow In DataGrid2.Rows
  6. If FILA.Cells("Tipo_Carne").Value = DataGrid1.CurrentCell.Value Then
  7. Agregar = "NO"
  8. Exit For
  9. End If
  10. Next
  11. 'Si el FLAG esta en SI agregamos la fila del DAtaGrid1 en el DataGrid2
  12. If Agregar = "SI" Then
  13. DataGrid2.Rows.Add(DataGrid1.CurrentRow)
  14. Else
  15. MsgBox("Este dato ya fue agregado.")
  16. End If
  17. End Sub

* Variable FLAG: Es una variable que sirve como un indicador para decidir cuando debe ocurrir una accion.

Última edición por TECKNOCK; 14/03/2011 a las 19:51
  #4 (permalink)  
Antiguo 15/03/2011, 07:38
 
Fecha de Ingreso: marzo-2011
Ubicación: Colombia
Mensajes: 17
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Datos duplicados en datagrid vb.net

Buenos dias... agradézco por sus respuestas, he llegado al siguiente código, pero todavia no me funciona, me puse a depurar el programa pero no me quiere entrar al condicional que tiene el mensaje... no sé si lo tengo bien escrito...help me!

NOTA: El datagrid1 se llama grilla_menu y el datagrid2 se llama grilla_dia


Código vb:
Ver original
  1. Private Sub grilla_menu_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla_menu.CellContentDoubleClick
  2.         Dim k As String
  3.         Dim tota, toot As Integer
  4.  
  5.         ' Se define una lista temporal de registro seleccionados
  6.        Dim rowSelected As New List(Of DataGridViewRow)()
  7.  
  8.         ' Se agrega el campo a la lista temporal
  9.        rowSelected.Add(grilla_menu.CurrentRow)
  10.  
  11.         ' Se agrega el item seleccionado a la grilla de destino
  12.        Dim existe = False
  13.         For Each row As DataGridViewRow In rowSelected
  14.             If Convert.ToString(row.Cells("Nombre Menu").Value).Equals(grilla_menu.CurrentRow) Then
  15.                 existe = True
  16.                 If (existe = True) Then
  17.                     MsgBox("Éste menú ya fué agregado", MsgBoxStyle.OkOnly, "INFORMACIÓN")
  18.                 Else
  19.                 End If
  20.  
  21.             End If
  22.             grilla_dia.Rows.Add(New Object() {False, row.Cells("Nombre Menu").Value, row.Cells("Valor").Value})
  23.  
  24.             toot = row.Cells("Valor").Value
  25.             tota = TextBox1.Text
  26.  
  27.             k = (toot + tota)
  28.  
  29.             TextBox1.Text = k
  30.         Next
  31.        
  32.     End Sub
  #5 (permalink)  
Antiguo 15/03/2011, 07:50
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Parece que te falta añadirle el valor aqui :


For Each row As DataGridViewRow In rowSelected
If Convert.ToString(row.Cells("Nombre Menu").Value).Equals(grilla_menu.CurrentRow.Cell("Nombre Menu").Value) Then

xq alli debes compararlo el valor de la celda del grilla_dia con el mismo valor de la celda del grilla_menu y no con la fila. Saludos!
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #6 (permalink)  
Antiguo 15/03/2011, 07:56
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Deseas agregar datos de grilla_menu a grilla_dia ? o viceversa?
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #7 (permalink)  
Antiguo 15/03/2011, 08:08
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Pruebalo de esta manera...

Código vb.net:
Ver original
  1. Private Sub grilla_menu_CellContentDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla_menu.CellContentDoubleClick
  2.         Dim k As String
  3.         Dim tota, toot As Integer
  4.        
  5.         ' Se agrega el item seleccionado a la grilla de destino
  6.         Dim existe = False
  7.  
  8.         For Each row As DataGridViewRow In grilla_dia.Rows
  9.             If Convert.ToString(row.Cells("Nombre Menu").Value).Equals(grilla_menu.CurrentRow.Cells("Nombre Menu").Value) Then
  10.                 existe = True
  11.             End If
  12.             If (existe = True) Then
  13.                     MsgBox("Éste menú ya fué agregado", MsgBoxStyle.OkOnly, "INFORMACIÓN")
  14.             Else
  15. grilla_dia.Rows.Add(grilla_menu.CurrentRow)
  16.  
  17.             toot = grilla_menu.CurrentRow.Cells("Valor").Value
  18.             tota = TextBox1.Text
  19.  
  20.             k = (toot + tota)
  21.  
  22.             TextBox1.Text = k
  23.                 End If
  24.            
  25.         Next
  26.        
  27.     End Sub
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #8 (permalink)  
Antiguo 16/03/2011, 08:29
 
Fecha de Ingreso: marzo-2011
Ubicación: Colombia
Mensajes: 17
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Datos duplicados en datagrid vb.net

Gracias Aquaventus, pero de esa manera no quiere entrar al For Each y no agrega nada.

Voy a partir desde cero otra véz:
Con el siguiente código el programa me agrega el registro del Datagrid1 que se llama "grilla_menu" al Datagrid2 que se llama "grilla_dia":

Código vb:
Ver original
  1. Private Sub grilla_menu_CellDoubleClick1(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles grilla_menu.CellDoubleClick
  2.  
  3.         Dim k As String
  4.         Dim tota, toot As Integer
  5.  
  6.         ' Se define una lista temporal de registro seleccionados
  7.        Dim rowSelected As New List(Of DataGridViewRow)()
  8.  
  9.         ' Se agrega el campo a la lista temporal
  10.        rowSelected.Add(grilla_menu.CurrentRow)
  11.  
  12.         ' Se agrega el item seleccionado a la grilla de destino
  13. 'Las dos columnas de grilla_dia se llaman "nombre" y "valor"
  14.        For Each row As DataGridViewRow In rowSelected
  15.             grilla_dia.Rows.Add(New Object() {row.Cells("nombre").Value, row.Cells("valor").Value})
  16.  
  17. 'y por último sumo la columna "valor" de grilla_dia y arrojo el resultado en un textbox llamado "VALOR"
  18.            toot = row.Cells("valor").Value
  19.             tota = VALOR.Text
  20.  
  21.             k = (toot + tota)
  22.  
  23.             VALOR.Text = k
  24.         Next
  25.  
  26.     End Sub


Si sabes de otra forma de agregar los registros al datagrid2 y que sea más fácil de controlar los datos duplicados te agradézco que me la enseñes.
Las columnas que necesito de grilla_menu se llaman "nombre" y "valor"
  #9 (permalink)  
Antiguo 16/03/2011, 08:33
 
Fecha de Ingreso: marzo-2011
Ubicación: Colombia
Mensajes: 17
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Datos duplicados en datagrid vb.net

Te lo agradecería mucho!
  #10 (permalink)  
Antiguo 16/03/2011, 08:43
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

haber darco1103 lo que estas haciendo alli es obtener la fila seleccionada, agregarlo en una lista(que no le veo la utilidad.... porque solo va a almacenar 1 fila siempre al hacer double_click), luego recorres tu "lista"(de 1 item... que no tiene sentido recorrerlo...) y luego agregarlo sin comparar que ya existe...
Se me hace raro que no realize lo que pides el codigo que te pase... en todo caso enviame tu proyecto con bd a mi correo para construir el codigo y pasartelo. Saludos.

PDT: mi correo esta debajo de mi avatar en la mariposa de msn.
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #11 (permalink)  
Antiguo 16/03/2011, 11:03
Avatar de TECKNOCK  
Fecha de Ingreso: agosto-2010
Mensajes: 80
Antigüedad: 13 años, 7 meses
Puntos: 1
Respuesta: Datos duplicados en datagrid vb.net

Prueba el código que te pasé.... te garantizo que funciona.

O quizá estás haciendo algo mal en otra parte de tu código.
  #12 (permalink)  
Antiguo 16/03/2011, 11:11
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

claro concuerdo con tecknock... solo que el modifica y lo hace a su manera... lo cual esta bien para que aprenda... pero no sigue una logica correcta a lo que esta pidiendo... en lo que realiza en su construccion de codigo... alli tienes 2 ejemplos de como hacerlo de manera correcta. Saludos!
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #13 (permalink)  
Antiguo 17/03/2011, 09:03
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Hola draco1103! Solucionado y probado en tu proyecto, este es el codigo :

Código vb.net:
Ver original
  1. Dim existe = False
  2.  
  3.         For Each row As DataGridViewRow In grilla_dia.Rows
  4.             If Convert.ToString(row.Cells(0).Value).Equals(grilla_menu.CurrentRow.Cells(2).Value) Then
  5.                 existe = True
  6.             End If
  7.         Next
  8.         If (existe = True) Then
  9.             MsgBox("Éste menú ya fué agregado", MsgBoxStyle.OkOnly, "INFORMACIÓN")
  10.         Else
  11.             grilla_dia.Rows.Add(grilla_menu.CurrentRow.Cells(2).Value, grilla_menu.CurrentRow.Cells(3).Value)
  12.  
  13.             toot = grilla_menu.CurrentRow.Cells("Valor").Value
  14.             tota = VALOR.Text
  15.  
  16.             k = (toot + tota)
  17.  
  18.             VALOR.Text = k
  19.         End If

Saludos!
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net
  #14 (permalink)  
Antiguo 17/03/2011, 10:54
 
Fecha de Ingreso: marzo-2011
Ubicación: Colombia
Mensajes: 17
Antigüedad: 13 años, 1 mes
Puntos: 0
De acuerdo Respuesta: Datos duplicados en datagrid vb.net


Gracias Aquaventus...sos mi ídolo!
  #15 (permalink)  
Antiguo 17/03/2011, 11:01
Avatar de Aquaventus  
Fecha de Ingreso: junio-2010
Ubicación: Lima-Peru , En el alba de la naturaleza
Mensajes: 2.105
Antigüedad: 13 años, 9 meses
Puntos: 267
Respuesta: Datos duplicados en datagrid vb.net

Por cierto a lo del redondeo es:
'2 es la cantidad de numeros despues del punto redondeado
Math.Round(TUDECIMAL,2)
__________________
Internet es tener todo el conocimiento global a tu disposición.
Desarrollo de Software - Ejemplos .Net

Etiquetas: datagrid, duplicados
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 11:23.