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

Filtrar Grid por campo fecha

Estas en el tema de Filtrar Grid por campo fecha en el foro de .NET en Foros del Web. Hola veran tengo un datagridview que lleno con datos del tipo de cambio del dolar, el problema es que tengo que filtrar esos datos por ...
  #1 (permalink)  
Antiguo 17/08/2009, 19:28
Avatar de jaullo  
Fecha de Ingreso: abril-2009
Mensajes: 994
Antigüedad: 15 años
Puntos: 30
Filtrar Grid por campo fecha

Hola veran tengo un datagridview que lleno con datos del tipo de cambio del dolar, el problema es que tengo que filtrar esos datos por fecha pero no he podido. El código que utilizo es el siguiente

Private Sub Aplicar_Filtro()

' filtrar por el campo Producto
'''''''''''''''''''''''''''''''''''''''''''''''''' ''
Dim ret As Integer = Filtrar_DataGridView( _
"Fecha", _
Convert.ToString(txtcriterio.Text.Trim), _
BindingSource1, _
DataGridView1, _
CType(cbocriterio.SelectedIndex, e_FILTER_OPTION))

If ret = 0 Then
' si no hay registros cambiar el color del txtbox
txtcriterio.BackColor = Color.Red
Else
txtcriterio.BackColor = Color.White
End If
' visualizar la cantidad de registros
Me.Text = ret & " Registros encontrados"
End Sub

#Region "grid"


' cadena de conexión para SQL EXPRESS en modo local
Private cs As String = VarGlobales.conex


Private Sub txtcriterio_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles txtcriterio.KeyUp
Try
' Inicializar la conexión y abrir
Using cn As SqlConnection = New SqlConnection(cs)
cn.Open()

' Inicializar DataAdapter indicando el sql para recuperar
'los registros de la tabla
Dim da As New SqlDataAdapter("SELECT fecha as Fecha,moneda as Moneda,venta as Venta,compra as Compra from tcambio", cn)
Dim dt As New DataTable ' crear un DataTable

' llenarlo
da.Fill(dt)

' enlazar el DataTable al BindingSource
BindingSource1.DataSource = dt
Me.DataGridView1.DataSource = dt
' agregar las opciones al combobox
With (cbocriterio)

'cargar los items de opciones para filtrar
.Items.Add("No filtrar")
.Items.Add("Que comience con")
.Items.Add("Que No comience con")
.Items.Add("Que contenga")
.Items.Add("Que No contenga")
.Items.Add("Que sea igual")

.DropDownStyle = ComboBoxStyle.DropDownList
.SelectedIndex = 1
End With
End Using
' errores
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try

txtcriterio.Focus()
If txtcriterio.Text = "" Then
cbocriterio.Items.Clear()
End If

End Sub

Private Sub txt_Filtro_TextChanged( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles txtcriterio.TextChanged

Aplicar_Filtro()

End Sub

#End Region


'Instanciar el componente BindingSource
Public BindingSource1 As Windows.Forms.BindingSource = New BindingSource

' enumeración para las opciones que se usarán
' para filtrar con el operador Like
Enum e_FILTER_OPTION
SIN_FILTRO = 0
CADENA_QUE_COMIENCE_CON = 1
CADENA_QUE_NO_COMIENCE_CON = 2
CADENA_QUE_CONTENGA = 3
CADENA_QUE_NO_CONTENGA = 4
CADENA_IGUAL = 5
End Enum


Function Filtrar_DataGridView( _
ByVal Columna As String, _
ByVal texto As String, _
ByVal BindingSource As BindingSource, _
ByVal DataGridView As DataGridView, _
Optional ByVal Opcion_Filtro As e_FILTER_OPTION = Nothing) As Integer

' verificar que el DataSource no esté vacio
If BindingSource1.DataSource Is Nothing Then
Return 0
End If

Try

Dim filtro As String = String.Empty

' Seleccionar la opción
Select Case Opcion_Filtro
Case e_FILTER_OPTION.CADENA_QUE_COMIENCE_CON
filtro = "like'" & texto.Trim & "%'"
Case e_FILTER_OPTION.CADENA_QUE_NO_COMIENCE_CON
filtro = "Not like '" & texto.Trim & "%'"
Case e_FILTER_OPTION.CADENA_QUE_NO_CONTENGA
filtro = "Not like '%" & texto.Trim & "%'"
Case e_FILTER_OPTION.CADENA_QUE_CONTENGA
filtro = "like '%" & texto.Trim & "%'"
Case e_FILTER_OPTION.CADENA_IGUAL
filtro = "='" & texto.Trim & "'"
End Select
' Opción para no filtrar
If Opcion_Filtro = e_FILTER_OPTION.SIN_FILTRO Then
filtro = String.Empty
End If

' armar el sql
If filtro <> String.Empty Then
filtro = "[" & Columna & "]" & filtro
End If

' asigar el criterio a la propiedad Filter del BindingSource
BindingSource.Filter = filtro
' enlzar el datagridview al BindingSource
DataGridView.DataSource = BindingSource.DataSource

' retornar la cantidad de registros encontrados
Return BindingSource.Count

' errores
Catch ex As Exception
' MsgBox(ex.Message.ToString, MsgBoxStyle.Critical)
End Try

Return 0

End Function

He tratado conviertiendo el texto, cambiando en el codigo el tipo de columna a date pero siempre me sale un error que dice:
No se puede realizar la operacion 'like' en system.datetime y system.string
Eso es porque en el codigo tengo definida la columna del grid como string, pero si la cambio a fecha me dice que no se puede convertir la columna fecha a datetime.

Espero me puedan ayudar.
  #2 (permalink)  
Antiguo 25/08/2009, 01:20
 
Fecha de Ingreso: junio-2008
Ubicación: Valencia
Mensajes: 152
Antigüedad: 15 años, 10 meses
Puntos: 3
Respuesta: Filtrar Grid por campo fecha

En la base de datos el campo fecha es de tipo datetime o string?
Si es Datetime el problema esta ahi, tendrias que convertir ese campo a un string (en la select).
No se si me he expliacado del todo bien.
  #3 (permalink)  
Antiguo 26/08/2009, 18:23
Avatar de jaullo  
Fecha de Ingreso: abril-2009
Mensajes: 994
Antigüedad: 15 años
Puntos: 30
Respuesta: Filtrar Grid por campo fecha

Si es de tipo date.

Como lo puedo convertir a string en el select?
  #4 (permalink)  
Antiguo 27/08/2009, 02:04
 
Fecha de Ingreso: junio-2008
Ubicación: Valencia
Mensajes: 152
Antigüedad: 15 años, 10 meses
Puntos: 3
Respuesta: Filtrar Grid por campo fecha

Yo suelo utilizar la funcion CAST
CASt(column_fecha AS CHARACTER(tamañoString))
  #5 (permalink)  
Antiguo 30/08/2009, 19:37
Avatar de jaullo  
Fecha de Ingreso: abril-2009
Mensajes: 994
Antigüedad: 15 años
Puntos: 30
Respuesta: Filtrar Grid por campo fecha

Gracias lo intentare
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:59.