Usuario
GridView asp.net variar el ancho de las columnas con el ratón

Pregunta
-
Hola compañeros,
Llevo varios días buscando en el foro como variar el ancho de las columnas con el ratón y no lo he encontrado.
El GridView que viene para asp.net no tiene propiedades como AutoSizeColumnMode, que si tiene el DataGridView que se usa en aplicaciones de escritorio. He visto como cambiar por código el ancho de las columnas utilizando los estilos, pero me gustaría saber si se podría hacer que la cabecera, al pasar el ratón por los límites de cada columna, cambiara el cursor y me permitiese arrastrar y así modificar el ancho de la misma.
Si el GridView no permite esta funcionalidad, ¿existe alguna otra forma de hacerlo? me parece haberlo visto en algunas páginas web.
Muchas gracias de antemano por vuestro tiempo.
José Antonio Arjona
- Editado José A. Arjona jueves, 8 de octubre de 2015 13:00
Todas las respuestas
-
El GridView no es capaz de hacerlo. Lo que hace es convertir el grid en HTML y enviar ese HTML al nevegador, el cual lo muestra. A partir de ese momento el GridView se destruye en el servidor y solo queda visible el HTML que se envió al navegador, así que el GridView no puede hacer nada en respuesta a los movimientos del ratón que se hagan en el navegador (el gridview ya no existe en ese momento, y aunque existiese se encontraría en otra máquina -- el servidor en lugar del navegador).
Esto significa que para conseguir lo que quieres tienes que usar código javascript que interactúe con el TABLE que se generó a partir del GridView. Tendrías que capturar el mousedown en una zona próxima al borde de la cabecera y luego según el movimiento del ratón cambiar la anchura de la columna manipulando el DOM.
Es algo complicadillo de hacer si no eres un experto en javascript y HTML. Te recomendaría usar algún control de terceras partes que genere por tí ese javascript. Por ejemplo, podrías usar el RadGrid de Telerik:
- Propuesto como respuesta Karen MalagónModerator viernes, 9 de octubre de 2015 22:28
- Marcado como respuesta Karen MalagónModerator lunes, 12 de octubre de 2015 18:47
- Desmarcado como respuesta José A. Arjona martes, 13 de octubre de 2015 9:21
- Votado como útil José A. Arjona martes, 13 de octubre de 2015 9:21
-
Hola José.
Para poder hacer lo que indicas, tendrás que hacerlo por código javacript o jquery. Existe un plugin para hacer esto.
Demo. y lo puedes descargar desde aquí
Para esto, cuando usas un plugin de jquery con un gridview, debes asegurarte que el gridview reendere el header, para que el plugin funcione.
Update: Aquí un ejemplo de como hacer esto.
Cambiar el tamaño de una columna de un GridView con el plug-in de jQuery Resizable Columns.
Espero que la respuesta te ayude.
Saludos,
@norrojas
- Editado Norberto Rojas jueves, 8 de octubre de 2015 16:29 Agregue información
- Propuesto como respuesta Karen MalagónModerator viernes, 9 de octubre de 2015 22:28
- Marcado como respuesta Karen MalagónModerator lunes, 12 de octubre de 2015 18:47
- Desmarcado como respuesta José A. Arjona martes, 13 de octubre de 2015 9:20
- Votado como útil José A. Arjona martes, 13 de octubre de 2015 9:22
-
-
Hola de nuevo José,
>> No reconoce el código HTML
Me ayudas con tu código, cómo estas intentando implementar el jquery?. No debería de haber problema, ya que el jquery es independiente, no importa si es c# o vb.net, ni la versión del Visual Studio.
Saludos,
@norrojas
-
Esta es la parte de aspx:
<%@ Page Language="vb" AutoEventWireup="true" CodeBehind="Central_de_Idiomas.aspx.vb" Inherits="Central_de_Idiomas.WebForm1" EnableEventValidation="false" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>CENTRAL DE IDIOMAS</title> <style type="text/css"> #form1 { width: 100%; height: 452px; } .auto-style1 { height: 20px; } .auto-style2 { width: 100%; height: 20px; } </style> </head> <body style="height: 0px"> <form id="form1" runat="server"> <div style="overflow:auto;"> <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None" style="margin-left: 10px" ShowHeaderWhenEmpty="True" AllowSorting="True" OnSorting="SortRecords" AllowPaging="True" PageSize="17"> <AlternatingRowStyle BackColor="White" /> <EditRowStyle BackColor="#7C6F57" /> <FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"/> <HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White"/> <PagerSettings Mode="NumericFirstLast" /> <PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#E3EAEB" /> <SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F8FAFA" /> <SortedAscendingHeaderStyle BackColor="#246B61" /> <SortedDescendingCellStyle BackColor="#D4DFE1" /> <SortedDescendingHeaderStyle BackColor="#15524A" /> <EmptyDataTemplate>No se encontraron registros</EmptyDataTemplate> </asp:GridView> </div> <asp:Panel ID="Panel1" runat="server" Width="100%" DefaultButton="butBuscarEspañol"> <table id="Table1" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="1" class="auto-style1"> <asp:CheckBox ID="ChkEspañol" runat="server" Checked="True" Height="20px" Text="Español" Width="91px" /> </td> <td tabindex="2" class="auto-style2"> <asp:TextBox ID="txtEspañol" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="3" class="auto-style1"> <asp:ImageButton ID="butBuscarEspañol" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel2" runat="server" Width="100%" DefaultButton="butBuscarIngles"> <table id="Table2" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="4" class="auto-style1"> <asp:CheckBox ID="ChkIngles" runat="server" Checked="True" Height="20px" Text="Inglés" Width="91px"/> </td> <td tabindex="5" class="auto-style2"> <asp:TextBox ID="txtIngles" input="txtIngles2" runat="server" Height="20px" Width="100%" ></asp:TextBox> </td> <td tabindex="6" class="auto-style1"> <asp:ImageButton ID="butBuscarIngles" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel3" runat="server" Width="100%" DefaultButton="butBuscarFrances"> <table id="Table3" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="7" class="auto-style1"> <asp:CheckBox ID="ChkFrances" runat="server" Checked="True" Height="20px" Text="Francés" Width="91px" /> </td> <td tabindex="8" class="auto-style2"> <asp:TextBox ID="txtFrances" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="9" class="auto-style1"> <asp:ImageButton ID="butBuscarFrances" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel4" runat="server" Width="100%" DefaultButton="butBuscarAleman"> <table id="Table4" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="10" class="auto-style1"> <asp:CheckBox ID="ChkAleman" runat="server" Checked="True" Height="20px" Text="Alemán" Width="91px" /> </td> <td tabindex="11" class="auto-style2"> <asp:TextBox ID="txtAleman" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="12" class="auto-style1"> <asp:ImageButton ID="butBuscarAleman" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel5" runat="server" Width="100%" DefaultButton="butBuscarPolaco"> <table id="Table5" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="13" class="auto-style1"> <asp:CheckBox ID="ChkPolaco" runat="server" Checked="True" Height="20px" Text="Polaco" Width="91px" /> </td> <td tabindex="14" class="auto-style2"> <asp:TextBox ID="txtPolaco" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="15" class="auto-style1"> <asp:ImageButton ID="butBuscarPolaco" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel6" runat="server" Width="100%" DefaultButton="butBuscarPortugues"> <table id="Table6" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="16" class="auto-style1"> <asp:CheckBox ID="ChkPortugues" runat="server" Checked="True" Height="20px" Text="Portugués" Width="91px" /> </td> <td tabindex="17" class="auto-style2"> <asp:TextBox ID="txtPortugues" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="18" class="auto-style1"> <asp:ImageButton ID="butBuscarPortugues" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Panel ID="Panel7" runat="server" Width="100%" DefaultButton="butBuscarCatalan"> <table id="Table7" runat="server" style="height:20px; margin-bottom: 0px; margin-top: 0px; border-collapse:collapse;"> <tr> <td tabindex="19" class="auto-style1"> <asp:CheckBox ID="ChkCatalan" runat="server" Checked="True" Height="20px" Text="Catalán" Width="91px" /> </td> <td tabindex="20" class="auto-style2"> <asp:TextBox ID="txtCatalan" runat="server" Height="20px" Width="100%"></asp:TextBox> </td> <td tabindex="21" class="auto-style1"> <asp:ImageButton ID="butBuscarCatalan" runat="server" Height="20px" ImageUrl="~/Images/Lupa.png" style="margin-left: 15px; margin-top: 0px" Width="27px" /> </td> </tr> </table> </asp:Panel> <asp:Label ID="lblTotal" runat="server" Width="89px" style="margin-top: 0px; margin-left: 7px;" Height="16px" Font-Bold="True"></asp:Label> <asp:ImageButton ID="butAñadir" runat="server" ImageUrl="~/Images/Añadir.png" style="margin-left: 0px; margin-top: 0px" Width="40px" ImageAlign="AbsMiddle" /> <asp:ImageButton ID="butModificar" runat="server" ImageUrl="~/Images/Editar.png" style="margin-left: 18px" Width="40px" ImageAlign="AbsMiddle" /> <asp:ImageButton ID="butEliminar" runat="server" ImageUrl="~/Images/Eliminar.png" style="margin-left: 18px; margin-top: 0px" Width="40px" ImageAlign="AbsMiddle" /> </form> </body> </html> <script id="grid" type="text/javascript" > function On(GridView) { if(GridView != null) { GridView.originalBgColor = GridView.style.backgroundColor; GridView.style.backgroundColor="#eeff00"; } } function Off(GridView) { if(GridView != null) { GridView.style.backgroundColor = GridView.originalBgColor; } } </script>
He hecho una tabla distinta por fila, porque es la única forma que he encontrado de hacer que el retorno pase el control al botón de búsqueda que hay para cada idioma.
La tabla se crea dinámicamente según los datos obtenidos de la BD, el código BV es el siguiente, verás que ya utilizo el javasript para resaltar las filas de la tabla al mover el ratón sobre ellas o para ordenar las columnas.
Imports System.Data Imports System.Drawing Imports Oracle.ManagedDataAccess.Client ' ODP.NET, Managed Driver Imports Oracle.ManagedDataAccess.Types Imports System.Windows Public Class WebForm1 Inherits System.Web.UI.Page Dim cmd As New OracleCommand Dim dr As OracleDataReader Dim oradb As String = "Data Source=mdesa2_unicode;User ID=central;Password=central" Public Shared table As New DataTable Public Shared textoUltimaBusqueda As String = "¤" ' la uso para que al ordenar se mantenga la tabla existente Public Shared idioma As String = "ESPAÑOL" Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Integer) As Short Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load, Me.Load, Me.Load If GridView1.Rows.Count = 0 Then Consultar(textoUltimaBusqueda, idioma) ' Consulto la BD, la 1ª vez será todo: ("", "ESPAÑOL") End If End Sub Public Sub butBuscar_Click(sender As Object, e As ImageClickEventArgs) Handles butBuscarEspañol.Click, butBuscarIngles.Click, butBuscarFrances.Click, butBuscarAleman.Click, butBuscarPolaco.Click, butBuscarPortugues.Click, butBuscarCatalan.Click table.Rows.Clear() ' Primero limpio la tabla de la búsqueda anterior Dim but As ImageButton = CType(sender, ImageButton) If but.ID = "butBuscarEspañol" Then textoUltimaBusqueda = txtEspañol.Text idioma = "ESPAÑOL" Else txtEspañol.Text = "" End If If but.ID = "butBuscarIngles" Then textoUltimaBusqueda = txtIngles.Text idioma = "INGLÉS" Else txtIngles.Text = "" End If If but.ID = "butBuscarFrances" Then textoUltimaBusqueda = txtFrances.Text idioma = "FRANCÉS" Else txtFrances.Text = "" End If If but.ID = "butBuscarAleman" Then textoUltimaBusqueda = txtAleman.Text idioma = "ALEMÁN" Else txtAleman.Text = "" End If If but.ID = "butBuscarPolaco" Then textoUltimaBusqueda = txtPolaco.Text idioma = "POLACO" Else txtPolaco.Text = "" End If If but.ID = "butBuscarPortugues" Then textoUltimaBusqueda = txtPortugues.Text idioma = "PORTUGUÉS" Else txtPortugues.Text = "" End If If but.ID = "butBuscarCatalan" Then textoUltimaBusqueda = txtCatalan.Text idioma = "CATALÁN" Else txtCatalan.Text = "" End If Consultar(textoUltimaBusqueda, idioma) ' Colsulto en la BD los registros que contienen el texto End Sub Public Sub butAñadir_Click(sender As Object, e As ImageClickEventArgs) Handles butAñadir.Click If Trim(txtEspañol.Text) <> "" Then ' sólo si existe algo en español 'PIDO NUEVA CLAVE Dim ID_CLAVE As Long ID_CLAVE = clave("ID_CENTRAL_DE_IDIOMAS") Dim conn As New OracleConnection(oradb) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = "INSERT INTO CENTRAL_DE_IDIOMAS(ID_CENTRAL_DE_IDIOMAS,ESPAÑOL,INGLÉS,FRANCÉS,ALEMÁN,POLACO,PORTUGUÉS,CATALÁN) VALUES (" & ID_CLAVE & ",'" & txtEspañol.Text & "','" & txtIngles.Text & "','" & txtFrances.Text & "','" & txtAleman.Text & "','" & txtPolaco.Text & "','" & txtPortugues.Text & "','" & txtCatalan.Text & "')" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try table.Rows.Clear() ' Primero limpio la tabla de la búsqueda anterior textoUltimaBusqueda = txtEspañol.Text Consultar(textoUltimaBusqueda, "ESPAÑOL") ' Consulto toda la BD Else Utilities.ShowAlert(Me, "AlertMessageBox", "No se ha añadido ningún registro") ' "\n" para meter CR+LF, "\t" tabulador End If End Sub Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged GridView1.SelectedRow.BackColor = Color.FromName("#24cb5f") ' Tiene que ser con valor exadecimal para que funcione txtEspañol.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(1).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtIngles.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(2).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtFrances.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(3).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtAleman.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(4).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtPolaco.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(5).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtPortugues.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(6).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView txtCatalan.Text = HttpUtility.HtmlDecode(GridView1.SelectedRow.Cells(7).Text).TrimEnd 'el TexBox muestra el código HTML que hay en el GridView End Sub Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound ' Resalto la fila que está debajo del puntero If e.Row.RowType = DataControlRowType.DataRow Then ' Se aplica sólo a las filas If ChkEspañol.Checked = True Then e.Row.Cells(1).Visible = True Else e.Row.Cells(1).Visible = False End If If ChkIngles.Checked = True Then e.Row.Cells(2).Visible = True Else e.Row.Cells(2).Visible = False End If If ChkFrances.Checked = True Then e.Row.Cells(3).Visible = True Else e.Row.Cells(3).Visible = False End If If ChkAleman.Checked = True Then e.Row.Cells(4).Visible = True Else e.Row.Cells(4).Visible = False End If If ChkPolaco.Checked = True Then e.Row.Cells(5).Visible = True Else e.Row.Cells(5).Visible = False End If If ChkPortugues.Checked = True Then e.Row.Cells(6).Visible = True Else e.Row.Cells(6).Visible = False End If If ChkCatalan.Checked = True Then e.Row.Cells(7).Visible = True Else e.Row.Cells(7).Visible = False End If 'e.Row.Attributes.Add("onMouseOver", "this.style.background='#eeff00';this.style.cursor='pointer'") 'e.Row.Attributes.Add("onMouseOut", "this.style.background='#ffffff'") e.Row.Attributes.Add("OnMouseOver", "On(this);") e.Row.Attributes.Add("OnMouseOut", "Off(this);") e.Row.Attributes("OnClick") = Page.ClientScript.GetPostBackClientHyperlink(Me.GridView1, "Select$" + e.Row.RowIndex.ToString) End If End Sub Protected Sub butEliminar_Click(sender As Object, e As ImageClickEventArgs) Handles butEliminar.Click If Not GridView1.SelectedRow Is Nothing Then ' sólo si existe algo en español Dim conn As New OracleConnection(oradb) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = " DELETE FROM CENTRAL_DE_IDIOMAS WHERE ID_CENTRAL_DE_IDIOMAS = '" & GridView1.SelectedRow.Cells(0).Text & "'" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try table.Rows.Clear() ' Primero limpio la tabla de la búsqueda anterior Consultar(textoUltimaBusqueda, "ESPAÑOL") ' Consulto toda la BD Else Utilities.ShowAlert(Me, "AlertMessageBox", "No se ha eliminado ningún registro") ' "\n" para meter CR+LF, "\t" tabulador End If End Sub Protected Sub butModificar_Click(sender As Object, e As ImageClickEventArgs) Handles butModificar.Click If Trim(txtEspañol.Text) <> "" And Not GridView1.SelectedRow Is Nothing Then ' sólo si existe algo en español Dim conn As New OracleConnection(oradb) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = " UPDATE CENTRAL_DE_IDIOMAS SET ESPAÑOL='" & txtEspañol.Text & "',INGLÉS='" & txtIngles.Text & "',FRANCÉS='" & txtFrances.Text & "',ALEMÁN='" & txtAleman.Text & "',POLACO='" & txtPolaco.Text & "',PORTUGUÉS='" & txtPortugues.Text & "',CATALÁN='" & txtCatalan.Text & "' WHERE ID_CENTRAL_DE_IDIOMAS='" & GridView1.SelectedRow.Cells(0).Text & "'" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try table.Rows.Clear() ' Primero limpio la tabla de la búsqueda anterior textoUltimaBusqueda = txtEspañol.Text Consultar(textoUltimaBusqueda, "ESPAÑOL") ' Consulto toda la BD Else Utilities.ShowAlert(Me, "AlertMessageBox", "No ha habido ningún cambio") ' "\n" para meter CR+LF, "\t" tabulador End If End Sub Protected Sub Consultar(texto As String, idioma As String) ' Busco el contenido de texto en un idioma Dim conn As New OracleConnection(oradb) Try ' Para capturar posible errores conn.Open() Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = "SELECT COUNT(*) AS TOTAL FROM CENTRAL_DE_IDIOMAS WHERE " & idioma & " LIKE '%" & texto & "%' ORDER BY ESPAÑOL" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex2 As InvalidOperationException Utilities.ShowAlert(Me, "AlertMessageBox", "Message: " & Ex2.Message) ' "\n" para meter CR+LF, "\t" tabulador Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try dr.Read() If dr.Item(0) > 0 Then lblTotal.Text = "Total: " & Format(dr.Item(0), "#,###,##0") Else lblTotal.Text = "" End If dr.Close() cmd.CommandText = "SELECT * FROM CENTRAL_DE_IDIOMAS WHERE " & idioma & " LIKE '%" & texto & "%' ORDER BY ESPAÑOL" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex2 As InvalidOperationException Utilities.ShowAlert(Me, "AlertMessageBox", "Message: " & Ex2.Message) ' "\n" para meter CR+LF, "\t" tabulador Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try Dim row As DataRow 'table.Clear() 'table.Columns.Clear() If table.Columns.Count = 0 Then table.Columns.Add(New DataColumn("ID", GetType(String))) table.Columns.Add(New DataColumn("Español", GetType(String))) table.Columns.Add(New DataColumn("Inglés", GetType(String))) table.Columns.Add(New DataColumn("Francés", GetType(String))) table.Columns.Add(New DataColumn("Alemán", GetType(String))) table.Columns.Add(New DataColumn("Polaco", GetType(String))) table.Columns.Add(New DataColumn("Portugués", GetType(String))) table.Columns.Add(New DataColumn("Catalán", GetType(String))) End If Session("LISTA") = table table.DefaultView.Sort = "" While dr.Read() table = Session("LISTA") row = table.NewRow row.Item(0) = dr.Item("ID_CENTRAL_DE_IDIOMAS") row.Item(1) = dr.Item("ESPAÑOL") row.Item(2) = dr.Item("INGLÉS") row.Item(3) = dr.Item("FRANCÉS") row.Item(4) = dr.Item("ALEMÁN") row.Item(5) = dr.Item("POLACO") row.Item(6) = dr.Item("PORTUGUÉS") row.Item(7) = dr.Item("CATALÁN") table.Rows.Add(row) End While ' Convert the DataTable to DataView. 'Dim dvTable As New DataView(table) GridView1.DataSource = table 'dvTable GridView1.DataBind() ' Siempre dejo seleccionada el primera fila If GridView1.Rows.Count > 0 Then GridView1.SelectedIndex = 0 Else GridView1.SelectedIndex = -1 ' quito la selección End If dr.Close() dr.Dispose() conn.Dispose() End Sub Protected Sub SortRecords(ByVal sender As Object, ByVal e As GridViewSortEventArgs) Dim sortExpression As String = e.SortExpression Dim direction As String ' = " ASC" 'Por defecto ascendente If SortDirection = SortDirection.Ascending Then SortDirection = SortDirection.Descending direction = " DESC" Else SortDirection = SortDirection.Ascending direction = " ASC" End If 'Consultar(textoUltimaBusqueda, idioma) ' Colsulto en la BD sólo el texto tecleado GridView1.DataSource = table table.DefaultView.Sort = sortExpression & direction ' Esto ordena por el resto de columnas GridView1.DataBind() End Sub Public Property SortDirection() As SortDirection Get If ViewState("SortDirection") Is Nothing Then ViewState("SortDirection") = SortDirection.Ascending End If Return DirectCast(ViewState("SortDirection"), SortDirection) End Get Set(ByVal value As SortDirection) ViewState("SortDirection") = value End Set End Property Function clave(Campo As String) As Long 'campo -> Nombre del campo que queremos obtener su clave. 'clave -> Devuelve el último valor almacenado y lo deja incrementado. Campo = UCase(Campo) 'búsqueda siempre en mayúsculas Dim conn As New OracleConnection(oradb) conn.Open() cmd.Connection = conn cmd.CommandType = CommandType.Text cmd.CommandText = "SELECT " & Campo & ".NEXTVAL FROM DUAL" Try ' Para capturar posible errores dr = cmd.ExecuteReader() Catch Ex As OracleException ' El argumento proporcionado para el método no es válido. Utilities.ShowAlert(Me, "AlertMessageBox", "Code: " & Ex.ErrorCode & ", " & Ex.Message) ' "\n" para meter CR+LF, "\t" tabulador Finally 'sentencias que se ejecutan independientemente si ocurrió o no el lanzamiento de la excepción. 'MsgBox(Err.Number & ", " & Err.Description) ' MsgBox ya no es Modal End Try dr.Read() clave = dr.Item("NEXTVAL") conn.Dispose() End Function Private Sub GridView1_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles GridView1.PageIndexChanging GridView1.PageIndex = e.NewPageIndex GridView1.DataSource = table GridView1.DataBind() End Sub Protected Overrides Sub Finalize() MyBase.Finalize() End Sub End Class Public Class Utilities Inherits System.Web.UI.Page Public Shared Sub ShowAlert(ByRef aspxPage As System.Web.UI.Page, ByVal strKey As String, ByVal Mensaje As String) 'ClientScript.RegisterStartupScript(Me.GetType(), "AlertMessageBox", "alert('" & Mensaje & "');", True) aspxPage.ClientScript.RegisterStartupScript(aspxPage.GetType(), strKey, "alert('" & Mensaje & "');", True) End Sub End Class
José Antonio Arjona