Todos nós já ouvimos sobre o maravilhoso Datagrid em ASP.Net↳.NET113 conteúdosNovidades do .NET 9 – o tipo genérico OrderedDictionaryDev (Back & Front) · dez 2024Novidades .NET 10: novas formas de uso do .NET CLIDev (Back & Front) · dez 2025Novidades do .NET 5: implementando um proxy reverso com YARP + ASP.NET 5Dev (Back & Front) · nov 2020Ver tudo em Dev (Back & Front) →, muito útil, aliás. Neste exemplo iremos criar a uma versão do datagrid.
Para criar uma classe DataGrid, o primeiro problema foi a eficiência. Ao aprender como obter registros de uma base de dados e exibi-los em uma tabela em sua página ASP, muitas vezes fazemos desta forma.
<table> <br /><% <br />Do Until objRec.EOF <br />%> <br /> <tr> <br /> <td><%=objRec("nome") %></td> <br /> <td><%=objRec("enderco") %></td> <br /> <td><%=objRec("email") %></td> <br /> </tr> <br /><% <br /> objRec.movenext <br />loop <br />%> <br /></table> Ainda mais eficaz é a utilização do método de GetRows do Recordset para preencher a 2 array dimensional . Então você já não tem que usar os recursos acessando o Recordset.
dim arTable <br />arTable = objRec.GetRows <br />objRec.Close <br />set objRec = nothingVocê tem agora 2 array dimensional, mas como o recordset armazena informação neste array?
arTable’s – 2 dimensões: arTable (TotalCols, TotalRows). Portanto, se o meu Recordset retornou 10 registros, seria arTable (3, 10) e você teria que ir de arTable (0, 0) para arTable (2, 9) para recuperar cada valor que você deve ir através do TotalCols, seguido pelo TotalRows. Você não sabe quantos registros vai retornar, assim, usamos a função UBound:
dim tCols, tRows <br />tCols = UBound(arTable, 1) <br />tRows = UBound(arTable, 2)Com um array de mais de uma dimensão que necessita abastecer UBound com um valor para indicar, que o elemento deseja o total. Como vimos acima, nos tCols para definir o total da primeira dimensão e tRows para o total da segunda dimensão. Com esta informação, através dos registros utilizando loop aninhado.
<table> <br /><% <br />Dim x, y <br />For x = 0 to tRows <br /> Response.Write "<tr>" <br /> For y = 0 to tCols <br /> Response.Write "<td>" & rTable(y, x) & "</td>" <br /> Next <br /> Response.Write "</tr>" <br />Next <br />%> Um bom modelo que podemos mover/encapsular em uma classe.
Quando a classe inicia estabelecemos nosso objeto connection e objeto Recordset, também definimos a variável Column Count para 0 para usar nas nossas próprias colunas e, finalmente, usamos a AutoColumns = true. É neste processo que você colocaria quaisquer predefinições que você deseja para sua classe.
private pAutoColumns, pConnStr, pSqlStr, intColCnt <br /> Private pOutPut, pConn, pRec, x, y, pArray <br /> Private Sub Class_Initialize() <br /> Set pConn = server.createobject("adodb.connection") <br /> Set pRec = server.createobject("adodb.recordset") <br /> intColCnt = 0 <br /> pAutoColumns = True <br /> End Sub Em seguida, criamos as regras que nos permitem definir as várias propriedades:
Public Property Let ConnectionString(strConn) <br /> pConnStr = strConn <br /> End Property <br /><br /> Public Property Let AutoColumns(bAutoCols) <br /> If bAutoCols = True or bAutoCols = False then <br /> pAutoColumns = bAutoCols <br /> End IF <br /> End Property <br /><br /> Public Property Let SqlString(strSql) <br /> pSqlStr = strSql <br /> End Property Agora sobre os métodos, procedimentos, para a sua classe, adicionamos a funcionalidade real para a classe:
Public Sub AddColumn(strColName) <br /> If intColCnt = 0 then <br /> pOutPut = "<table width='100%' border=1 cellpadding=0 cellspacing=0>" & vbcrlf <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> End If <br /> pOutPut = pOutPut & "<td><strong>" & strColName & "</strong></td>" & vbcrlf <br /> intColCnt = intColCnt + 1 <br /> End Sub Se optar por especificar a nossa própria column names, então nós chamamos este método para adicionar um column names. Ele apenas acrescenta uma nova célula de nosso grid (tabela) para cada coluna, se quisermos iniciar a linha da tabela e se está em 0. Em qualquer outro momento podemos acrescentar a célula, ou não, se você usar AutoColumns.
Public Sub Bind <br /> pConn.Open pConnStr <br /> Set pRec = pConn.Execute(pSqlStr) <br /> If pAutoColumns = True then <br /> 'atribuir nomes de coluna retornados <br /> pOutPut = "<table width='100%' border=1 cellpadding=0 cellspacing=0>" & vbcrlf <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> Redim pColNames(pRec.Fields.Count) <br /> For x = 0 to pRec.Fields.Count - 1 <br /> pOutPut = pOutPut & "<td>" & pRec.Fields(x).Name & "</td>" & vbcrlf <br /> Next <br /> End If <br /> pOutPut = pOutPut & "</tr>" & vbcrlf <br /> pArray = pRec.GetRows <br /> For x = 0 to UBound(pArray, 2) <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> For y = 0 to UBound(pArray, 1) <br /> pOutPut = pOutPut & "<td>" & pArray(y, x) & "</td>" & vbcrlf <br /> Next <br /> pOutPut = pOutPut & "</tr>" & vbcrlf <br /> Next <br /> pOutPut = pOutPut & "</table>" & vbcrlf <br /> Response.Write pOutPut <br /> End Sub Basicamente, nós abrimos o recordset, se AutoColums = true então ficamos com os campos nomes e criamos células para eles ou vamos com o custom column names. Então usamos o código para percorrer a nossa matriz de valores. Tudo isto está a ser concatenado a uma string de saída, que é finalmente escrita para o browser no final.
Usando a classe em uma página ASP, salve-o como DataGrid.asp em sua pasta wwwroot, foi usado o nwind.mdb para o banco de dados↳Banco de dados134 conteúdosSQL ou NoSQL: eis a questão!!Data · mar 2020Banco de dados: como organizar e dar segurança para milhões de dados de loteriasData · mai 20215 serviços gratuitos na cloud para bancos de dados PostgresData · fev 2025Ver tudo em Data →.
Estrutura do banco:
[nwind]
[i]ID – autonum
Nome – texto
Profissão – texto
Fone – texto[/i]
<%@ LANGUAGE="VBSCRIPT" %> <br /><% option explicit %> <br /><% response.buffer=true %> <br /><html> <br /><head> <br /> <title>DataGrid Teste</title> <br /></head> <br /><!-- #include file="DataGrid.asp"--> <br /><body> <br /><% <br />dim meuDataGrid, mapPath <br />Set meuDataGrid= New caDataGrid <br />mapPath = "nwind.mdb" <br />' conexao <br />meuDataGrid.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="& Server.MapPath(mapPath) <br />meuDataGrid.SqlString = "select nome, profissao, fone from cadastro" <br />meuDataGrid.Bind <br />set meuDataGrid= nothing <br /><br />'agora permite definir nossas próprias colunas<br />response.write "<br><br>" <br />Set meuDataGrid= New caDataGrid <br />meuDataGrid.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="& Server.MapPath(mapPath) <br />meuDataGrid.SqlString = "select nome, profissao, fone from cadastro" <br />meuDataGrid.AutoColumns = false <br />meuDataGrid.AddColumn("nome") <br />meuDataGrid.AddColumn("profissao") <br />meuDataGrid.AddColumn("fone") <br />meuDataGrid.Bind <br />set meuDataGrid= nothing <br />%> <br /></body> <br /></html>Abaixo o código completo
<% <br />Class caDataGrid <br /> ' variaveis private<br /> private pAutoColumns, pConnStr, pSqlStr, intColCnt <br /> Private pOutPut, pConn, pRec, x, y, pArray <br /><br />'este é executado quando você cria uma referência para a classe caDataGrid <br /> Private Sub Class_Initialize() <br /> Set pConn = server.createobject("adodb.connection") <br /> Set pRec = server.createobject("adodb.recordset") <br /> intColCnt = 0 <br /> pAutoColumns = True <br /> End Sub <br /><br /> 'Propriedades - todos writable<br /> Public Property Let ConnectionString(strConn) <br /> pConnStr = strConn <br /> End Property <br /><br /> Public Property Let AutoColumns(bAutoCols) <br /> If bAutoCols = True or bAutoCols = False then <br /> pAutoColumns = bAutoCols <br /> End IF <br /> End Property <br /><br /> Public Property Let SqlString(strSql) <br /> pSqlStr = strSql <br /> End Property <br /><br /> 'Metodos <br /> Public Sub AddColumn(strColName) <br /> If intColCnt = 0 then <br /> pOutPut = "<table width='100%' border=1 cellpadding=0 cellspacing=0>" & vbcrlf <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> End If <br /> pOutPut = pOutPut & "<td><strong>" & strColName & "</strong></td>" & vbcrlf <br /> intColCnt = intColCnt + 1 <br /> End Sub <br /><br /> Public Sub Bind <br /> pConn.Open pConnStr <br /> Set pRec = pConn.Execute(pSqlStr) <br /> If pAutoColumns = True then <br /> 'atribuir nomes de coluna retornados<br /> pOutPut = "<table width='100%' border=1 cellpadding=0 cellspacing=0>" & vbcrlf <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> Redim pColNames(pRec.Fields.Count) <br /> For x = 0 to pRec.Fields.Count - 1 <br /> pOutPut = pOutPut & "<td>" & pRec.Fields(x).Name & "</td>" & vbcrlf <br /> Next <br /> End If <br /> pOutPut = pOutPut & "</tr>" & vbcrlf <br /> pArray = pRec.GetRows <br /> For x = 0 to UBound(pArray, 2) <br /> pOutPut = pOutPut & "<tr>" & vbcrlf <br /> For y = 0 to UBound(pArray, 1) <br /> pOutPut = pOutPut & "<td>" & pArray(y, x) & "</td>" & vbcrlf <br /> Next <br /> pOutPut = pOutPut & "</tr>" & vbcrlf <br /> Next <br /> pOutPut = pOutPut & "</table>" & vbcrlf <br /> Response.Write pOutPut <br /> End Sub <br /><br />'isso é quando finalizamos nossa referência caDataGrid<br /> Private Sub Class_Terminate() <br /> pOutPut = "" <br /> pRec.Close <br /> Set pRec = nothing <br /> pconn.close <br /> Set pConn = nothing <br /> End Sub <br /><br />End Class <br />%> 





