Usuário com melhor resposta
Ordem crescente Classe, Structure

Pergunta
-
Tenho um DataGridView, e separo Nomes de Responsavel com seu respectivo beneficiario. Mas gostaria de saber como posso colocar os nomes dos beneficiarios em ordem crescente (ordenado pela data de nascimento).
Meu Código
Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Adicionar colunas With DataGridView1 .Columns.Add("CPF", "CPF") .Columns(0).Width = 150 .Columns.Add("NomeResponsavel", "NomeResponsavel") .Columns(1).Width = 190 .Columns.Add("NomeCrianca", "NomeCrianca") .Columns(2).Width = 190 .Columns.Add("DataNascimento", "Data de Nascimento") .Columns(3).Width = 160 End With ' Adicionando linhas DataGridView1.Rows.Add(10) 'Adicionando dados ao grid DataGridView1.Rows(0).Cells(0).Value = "02398979784" DataGridView1.Rows(1).Cells(0).Value = "02398979784" DataGridView1.Rows(2).Cells(0).Value = "02476853640" DataGridView1.Rows(3).Cells(0).Value = "02772956962" DataGridView1.Rows(4).Cells(0).Value = "03244072704" DataGridView1.Rows(5).Cells(0).Value = "03244072704" DataGridView1.Rows(6).Cells(0).Value = "03244072704" DataGridView1.Rows(7).Cells(0).Value = "03614306801" DataGridView1.Rows(8).Cells(0).Value = "04259946609" DataGridView1.Rows(9).Cells(0).Value = "04259946609" DataGridView1.Rows(10).Cells(0).Value = "05402838860" DataGridView1.Rows(0).Cells(1).Value = "Marcos Vilela" DataGridView1.Rows(1).Cells(1).Value = "Marcos Vilela" DataGridView1.Rows(2).Cells(1).Value = "Pedro Nunes" DataGridView1.Rows(3).Cells(1).Value = "Fernanda Macedo" DataGridView1.Rows(4).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(5).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(6).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(7).Cells(1).Value = "Enrico Fauze" DataGridView1.Rows(8).Cells(1).Value = "Monica Chicarino" DataGridView1.Rows(9).Cells(1).Value = "Monica Chicarino" DataGridView1.Rows(10).Cells(1).Value = "GUSTAVO ZANARDI " DataGridView1.Rows(0).Cells(2).Value = "Fernando Vilela" DataGridView1.Rows(1).Cells(2).Value = "Patricia Vilela" DataGridView1.Rows(2).Cells(2).Value = "Rafael Nunes" DataGridView1.Rows(3).Cells(2).Value = "Marcela Macedo" DataGridView1.Rows(4).Cells(2).Value = "Vitor Cavalieri Teixeira" DataGridView1.Rows(5).Cells(2).Value = "Franciana Cavalieri Teixeira" DataGridView1.Rows(6).Cells(2).Value = "Jair Cavalieri Teixeira" DataGridView1.Rows(7).Cells(2).Value = "Marcos Fauze" DataGridView1.Rows(8).Cells(2).Value = "Greta Chicarino" DataGridView1.Rows(9).Cells(2).Value = "Adam Chicarino " DataGridView1.Rows(10).Cells(2).Value = "Olavo Zanardi" DataGridView1.Rows(0).Cells(3).Value = "01/12/2011" DataGridView1.Rows(1).Cells(3).Value = "10/10/2012" DataGridView1.Rows(2).Cells(3).Value = "05/09/2005" DataGridView1.Rows(3).Cells(3).Value = "07/09/2004" DataGridView1.Rows(4).Cells(3).Value = "11/08/2008" DataGridView1.Rows(5).Cells(3).Value = "12/02/2007" DataGridView1.Rows(6).Cells(3).Value = "16/01/2006" DataGridView1.Rows(7).Cells(3).Value = "22/03/2012" DataGridView1.Rows(8).Cells(3).Value = "05/05/2013" DataGridView1.Rows(9).Cells(3).Value = "04/06/2010" DataGridView1.Rows(10).Cells(3).Value = "01/07/2003" End Sub Private Structure Beneficiario Friend Nome As String Friend Data As String Friend Sub New(ByRef Nome As String, ByRef Data As String) Me.Nome = Nome Me.Data = Data End Sub End Structure Private Class Responsavel Friend CPF As String Friend Nome As String Friend Beneficiarios() As Beneficiario Friend Shared Function Procurar(ByRef List As System.Collections.ObjectModel.Collection(Of Responsavel), ByRef CPF As String) As Responsavel For Each R As Responsavel In List If R.CPF = CPF Then Return R Next R Return Nothing End Function Friend Sub Adicionar(ByRef Nome As String, ByRef Data As String) ReDim Preserve Me.Beneficiarios(0 To Me.Beneficiarios.Length) Me.Beneficiarios(Me.Beneficiarios.Length - 1) = New Beneficiario(Nome, Data) End Sub Friend Sub New(ByRef CPF As String, ByRef Nome As String, ByRef Beneficiario As String, ByRef Data As String) Me.CPF = CPF Me.Nome = Nome Me.Beneficiarios = New Beneficiario() {New Beneficiario(Nome, Data)} End Sub End Class Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim List As New System.Collections.ObjectModel.Collection(Of Responsavel) For Each Row As DataGridViewRow In DataGridView1.Rows Dim Procurado As Responsavel = Responsavel.Procurar(List, CStr(Row.Cells(0).Value)) If Procurado Is Nothing Then List.Add(New Responsavel(CStr(Row.Cells(0).Value), CStr(Row.Cells(1).Value), CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value))) Else Procurado.Adicionar(CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value)) End If Next Row Dim Text As String = "" For Each R As Responsavel In List Text += "RESPONSAVEL: " + R.Nome + vbNewLine + "CPF: " + R.CPF + vbNewLine For Each B As Beneficiario In R.Beneficiarios Text += "BENEFICIARIO: " + B.Nome + "DATA DE NASCIMENTO: " + B.Data + vbNewLine Next B Next R TextBox1.Text = Text End Sub End Class
Respostas
-
Olá tudo bem quando vc faz ordenado recebe sua listaOrdenado sua variavel ordenado já contém todos os seus dados ordenados pela data de nascimento, basta iterar pela lista de ordenado para jogar os dados nas textbox e mostrar os dados como quer tipo assim :
For Each item in ordenado Text += "Responsavel " & item.Nome & newVbLine & 'assim continua igual faz...
Veja se consegue.. Não precisa ficar nervosa rs.
- Marcado como Resposta Giovani Cr segunda-feira, 7 de abril de 2014 20:20
Todas as Respostas
-
-
-
Olá veja estes exemplos :
Apresentando genericos em VB.Net
Veja se consegue entender o conceito que lhe ajudo a implementar.
-
Bom no curso que eu fiz, vi alguns exemplos bem básicos
Como:
Dim lstEmpreg As New List(Of String) ' Adiciona alguns nomes à lista lstEmpreg.Add("João Paulo") lstEmpreg.Add("Pedro Sousa") lstEmpreg.Add("Luís Nascimento") lstEmpreg.Add("Carlos Sousa") lstEmpreg.Add("Nuno Luís")
Mas eu só não consegui entender como e onde vou criar uma lista responsavel e usar esse Expression com o método de extensão OrderBy(), pois ja tenho uma lista List e outra Procurado
Não posso criar um OrderBy abaixo na Lista Procurado?
Dim List As New System.Collections.ObjectModel.Collection(Of Responsavel) For Each Row As DataGridViewRow In DataGridView1.Rows Dim Procurado As Responsavel = Responsavel.Procurar(List, CStr(Row.Cells(0).Value)) If Procurado Is Nothing Then List.Add(New Responsavel(CStr(Row.Cells(0).Value), CStr(Row.Cells(1).Value), CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value))) Else Procurado.Adicionar(CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value)) End If
- Editado AndreiaMeiga segunda-feira, 31 de março de 2014 21:44
-
Olá pode sim, desde que Procurado seja uma coleção e pode usar os métodos de extensão olhe este exemplo :
Public Class Form1 Dim lista As New List(Of Procurado) Class Procurado Private _nome As String Private _id As Integer Private _Apelido As String Public Property Nome() As String Get Return _nome End Get Set(value As String) _nome = value End Set End Property Public Property id() As Integer Get Return _id End Get Set(value As Integer) _id = value End Set End Property Public Property Apelido() As String Get Return _Apelido End Get Set(value As String) _Apelido = value End Set End Property End Class Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click DataGridView1.DataSource = vbNull 'usando metodo de extensao order by p ordenar Dim ordernado As List(Of Procurado) = lista.OrderBy(Function(order As Procurado) order.Apelido).ToList() 'aqui a grid vai ser ordenado pelo campo Apelido DataGridView1.DataSource = ordernado End Sub Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load Dim cont As Integer = 10 For index = 1 To 10 Dim classe As New Procurado() classe.Apelido = cont.ToString() classe.id = index classe.Nome = "TESTE" & index lista.Add(classe) cont = cont - 1 Next DataGridView1.AutoGenerateColumns = True DataGridView1.DataSource = lista End Sub End Class
É um projeto simples mas um bom exemplo pra começar, veja q tenho a classe com suas propriedades, e carrego a grid com a coleção depois no click do botão eu ordeno novamente a grid, poderia ser com quaisquer um dos campos. muito mais simples,quando pegar o jeito nunca mais vai usar DataSet rs.
-
-
Muito bom seu exemplo, mas ainda não conseguir inserir ele no meu exemplo.
No meu caso não posso mexer no DataGrid, apenas pegar os dados e manipular
Tentei colocar OrderBy como no exemplo que você me deu, mas não deu nenhum resultado
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim List As New System.Collections.ObjectModel.Collection(Of Responsavel) For Each Row As DataGridViewRow In DataGridView1.Rows Dim Procurado As Responsavel = Responsavel.Procurar(List, CStr(Row.Cells(0).Value)) If Procurado Is Nothing Then List.Add(New Responsavel(CStr(Row.Cells(0).Value), CStr(Row.Cells(1).Value), CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value))) Else Procurado.Adicionar(CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value))
'ADICIONEI ESSA LINHA,
Procurado.Beneficiarios.OrderBy(Function(order As Beneficiario) order.Data).ToList() End If Next Row Dim Text As String = "" For Each R As Responsavel In List Text += "RESPONSAVEL: " + R.Nome + vbNewLine + "CPF: " + R.CPF + vbNewLine For Each B As Beneficiario In R.Beneficiarios Text += "BENEFICIARIO: " + B.Nome + " - " + B.Data + vbNewLine Next B Next R TextBox1.Text = Text End Sub
-
Está quase lá, só que agora vc não pode carregar seu datagrid igual fez antes, no seu 1 post,e sim usar uma classe que com cada campo necessario seja criado uma propriedade igual eu fiz. Você criou a classe para carregar a grid, mudou o modo como popula o seu datagrid ? Se não ou estiver duvida de como fazer posta ai.
-
Então, na verdade o DataGrid é carregado de um arquivo externo excel, eu só populei desse jeito para ficar mais fácil de entender.
Private Sub btnImportar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImportar.Click Dim OpenFileDialog1 As New OpenFileDialog Dim nomePlanilha As String = txtNomePlanilha.Text Dim FileName As String = "" Try Dim arquivo As New OpenFileDialog 'Abrimos a seleção do arquivo excel If arquivo.ShowDialog = Windows.Forms.DialogResult.OK Then Me.DataGridView1.DataSource = "" Dim da As OleDbDataAdapter Dim dt As DataTable Dim conexao_Excel As String = "" Try If rb2007.Checked = True Then conexao_Excel = "Provider=Microsoft.ACE.OLEDB.12.0;" & "data source=" & arquivo.FileName & "; " & "Extended Properties=Excel 12.0;" ElseIf rb2003.Checked = True Then conexao_Excel = "Provider=Microsoft.Jet.OleDb.4.0;data source=" & arquivo.FileName & ";Extended Properties=Excel 8.0;" End If Catch ex As Exception MessageBox.Show(ex.Message) Exit Sub End Try If txtNomePlanilha.Text = String.Empty Then MsgBox("Por favor preencher o nome da planilha", MsgBoxStyle.Critical, "Dmed exporta") Else ' cria um novo dataadapter da = New OleDbDataAdapter("SELECT [Nº NFS-e],[Data Hora NFE],[CPF/CNPJ do Tomador],[Razão Social do Tomador]," & _ "[Discriminação dos Serviços] FROM [" & nomePlanilha & "$] ORDER BY [CPF/CNPJ do Tomador]", conexao_Excel) ' ORDER BY [CPF/CNPJ do Tomador] End If ' preenche a tabela com dados da planilha Excel dt = New DataTable da.Fill(dt) ' vincula o modo de visao padrão da tabela ao datagrid DataGridView1.DataSource = dt Me.DataGridView1.AllowUserToAddRows = False Else Exit Sub End If Catch ex As Exception MsgBox("Verifique se não existe linhas fazias no arquivo do excel ou se você digitou o nome da planilha corretamente", MsgBoxStyle.Critical, "Dmed Exporta") MessageBox.Show(ex.Message) btnGerarTxt.Enabled = False End Try End Sub
-
-
-
rs, é simples olhe este exemplo :
'aqui onde vc carrega seu datatable dt = New DataTable da.Fill(dt) 'CRIE UMA CLASSE IGUAL A QUE EU FIZ NO MEU EXEMPLO COM 'AS PROPRIEDADES QUE VAI NECESSITAR E SO PASSAR OS 'DADOS P CLASSE P NAO MEXER MTO NA SUA ESTRUTURA 'cria o array q pode ser usado orderby Dim dados As New List(Of Procurado) For Each d In dt.Rows 'declara a classe com e passa os dados p as propriedades Dim p As New Procurado() p.Apelido = d("Apelido") 'todos os seus dadoss 'agora add no array dados.Add(p) Next 'agora vc pode ordenar o array como quiser dados.OrderBy(Function(o As Procurado) o.Nome).ToList() DataGridView1.DataSource = dados
Veja como é simples, não alterei sua estrutura e vai ser simples de ordenar por onde desejar, qualquer duvida avise.
-
Olá Andréia ou se linq com essa solução seria mais simples de implementar :
Dim enumeravel As IEnumerable(Of DataRow) = From row In dt.AsEnumerable() Order By row("suacolunaquedesejaserordenada") Select row
Dim d As New DataTable()
d = enumeravel.CopyToDataTable()datagridView1.DataSource = d
- Editado Daniel Brito br sexta-feira, 4 de abril de 2014 01:16
-
Ola Daniel,
Eu entendi bem seus exemplos, só não sei como inserir no meu problema. Veja o que eu tentei fazer
Public Class Form1 Dim listaOrdernado As New List(Of ordenado) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 'Adicionar colunas With DataGridView1 .Columns.Add("CPF", "CPF") .Columns(0).Width = 150 .Columns.Add("NomeResponsavel", "NomeResponsavel") .Columns(1).Width = 190 .Columns.Add("NomeCrianca", "NomeCrianca") .Columns(2).Width = 190 .Columns.Add("DataNascimento", "Data de Nascimento") .Columns(3).Width = 160 End With ' Adicionando linhas DataGridView1.Rows.Add(10) 'Adicionando dados ao grid DataGridView1.Rows(0).Cells(0).Value = "02398979784" DataGridView1.Rows(1).Cells(0).Value = "02398979784" DataGridView1.Rows(2).Cells(0).Value = "02476853640" DataGridView1.Rows(3).Cells(0).Value = "02772956962" DataGridView1.Rows(4).Cells(0).Value = "03244072704" DataGridView1.Rows(5).Cells(0).Value = "03244072704" DataGridView1.Rows(6).Cells(0).Value = "03244072704" DataGridView1.Rows(7).Cells(0).Value = "03614306801" DataGridView1.Rows(8).Cells(0).Value = "04259946609" DataGridView1.Rows(9).Cells(0).Value = "04259946609" DataGridView1.Rows(10).Cells(0).Value = "05402838860" DataGridView1.Rows(0).Cells(1).Value = "Marcos Vilela" DataGridView1.Rows(1).Cells(1).Value = "Marcos Vilela" DataGridView1.Rows(2).Cells(1).Value = "Pedro Nunes" DataGridView1.Rows(3).Cells(1).Value = "Fernanda Macedo" DataGridView1.Rows(4).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(5).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(6).Cells(1).Value = "RAFAEL LIMA CAVALIERI TEIXEIRA" DataGridView1.Rows(7).Cells(1).Value = "Enrico Fauze" DataGridView1.Rows(8).Cells(1).Value = "Monica Chicarino" DataGridView1.Rows(9).Cells(1).Value = "Monica Chicarino" DataGridView1.Rows(10).Cells(1).Value = "GUSTAVO ZANARDI " DataGridView1.Rows(0).Cells(2).Value = "Fernando Vilela" DataGridView1.Rows(1).Cells(2).Value = "Patricia Vilela" DataGridView1.Rows(2).Cells(2).Value = "Rafael Nunes" DataGridView1.Rows(3).Cells(2).Value = "Marcela Macedo" DataGridView1.Rows(4).Cells(2).Value = "Vitor Cavalieri Teixeira" DataGridView1.Rows(5).Cells(2).Value = "Franciana Cavalieri Teixeira" DataGridView1.Rows(6).Cells(2).Value = "Jair Cavalieri Teixeira" DataGridView1.Rows(7).Cells(2).Value = "Marcos Fauze" DataGridView1.Rows(8).Cells(2).Value = "Greta Chicarino" DataGridView1.Rows(9).Cells(2).Value = "Adam Chicarino " DataGridView1.Rows(10).Cells(2).Value = "Olavo Zanardi" DataGridView1.Rows(0).Cells(3).Value = "01/12/2012" DataGridView1.Rows(1).Cells(3).Value = "10/10/2011" DataGridView1.Rows(2).Cells(3).Value = "05/09/2005" DataGridView1.Rows(3).Cells(3).Value = "07/09/2006" DataGridView1.Rows(4).Cells(3).Value = "11/08/2007" DataGridView1.Rows(5).Cells(3).Value = "12/02/2004" DataGridView1.Rows(6).Cells(3).Value = "16/01/2003" DataGridView1.Rows(7).Cells(3).Value = "22/03/2009" DataGridView1.Rows(8).Cells(3).Value = "05/05/2013" DataGridView1.Rows(9).Cells(3).Value = "04/06/2010" DataGridView1.Rows(10).Cells(3).Value = "01/07/2003" End Sub Private Structure Beneficiario Friend Nome As String Friend Data As String Friend Sub New(ByRef Nome As String, ByRef Data As String) Me.Nome = Nome Me.Data = Data End Sub End Structure Private Class Responsavel Friend CPF As String Friend Nome As String Friend Beneficiarios() As Beneficiario Friend Shared Function Procurar(ByRef List As System.Collections.ObjectModel.Collection(Of Responsavel), ByRef CPF As String) As Responsavel For Each R As Responsavel In List If R.CPF = CPF Then Return R Next R Return Nothing End Function Friend Sub Adicionar(ByRef Nome As String, ByRef Data As String) ReDim Preserve Me.Beneficiarios(0 To Me.Beneficiarios.Length) Me.Beneficiarios(Me.Beneficiarios.Length - 1) = New Beneficiario(Nome, Data) End Sub Friend Sub New(ByRef CPF As String, ByRef Nome As String, ByRef BNome As String, ByRef Data As String) Me.CPF = CPF Me.Nome = Nome Me.Beneficiarios = New Beneficiario() {New Beneficiario(BNome, Data)} End Sub End Class Class ordenado Private _cpf As String Private _nomeResponsavel As String Private _nomeCrianca As String Private _dataNascimento As String Public Property cpf() As String Get Return _cpf End Get Set(ByVal value As String) _cpf = value End Set End Property Public Property nomeResponsavel() As String Get Return _nomeResponsavel End Get Set(ByVal value As String) _nomeResponsavel = value End Set End Property Public Property nomeCrianca() As String Get Return _nomeCrianca End Get Set(ByVal value As String) _nomeCrianca = value End Set End Property Public Property dataNascimento() As String Get Return _dataNascimento End Get Set(ByVal value As String) _dataNascimento = value End Set End Property End Class Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Inserir Valores do DataGrid na Lista Criada For i As Integer = 0 To DataGridView1.Rows.Count - 1 Dim objProcurado As New ordenado() objProcurado.CPF = DataGridView1.Rows(i).Cells(0).Value objProcurado.NomeResponsavel = DataGridView1.Rows(i).Cells(1).Value objProcurado.NomeCrianca = DataGridView1.Rows(i).Cells(2).Value objProcurado.DataNascimento = DataGridView1.Rows(i).Cells(3).Value listaOrdernado.Add(objProcurado) Next 'Cria uma outra Lista de procurado Dim ordernado As List(Of ordenado) 'Ordenando a lista ordernado = listaOrdernado.OrderBy(Function(order As ordenado) order.dataNascimento).ToList() 'Nesse código eu separo Responsavel com seu (s) respectivos beneficiarios pelo Cpf e depois exporto para um textbox 'Eu preciso que dentro do textbox apareça os beneficiarios em ordem de nascimento Dim List As New System.Collections.ObjectModel.Collection(Of Responsavel) For Each Row As DataGridViewRow In DataGridView1.Rows Dim Procurado As Responsavel = Responsavel.Procurar(List, CStr(Row.Cells(0).Value)) If Procurado Is Nothing Then List.Add(New Responsavel(CStr(Row.Cells(0).Value), CStr(Row.Cells(1).Value), CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value))) Else Procurado.Adicionar(CStr(Row.Cells(2).Value), CStr(Row.Cells(3).Value)) End If Next Row Dim Text As String = "" For Each R As Responsavel In List Text += "RESPONSAVEL: " + R.Nome + vbNewLine + "CPF: " + R.CPF + vbNewLine For Each B As Beneficiario In R.Beneficiarios Text += "BENEFICIARIO: " + B.Nome + "DATA DE NASCIMENTO: " + B.Data + vbNewLine Next B Next R TextBox1.Text = Text End Sub End Class
Agora como posso "jogar" a lista ordenado na minha estrutura? Pois
eu separo Responsavel com seu (s) respectivos beneficiarios pelo Cpf e depois exporto para um textbox
Eu preciso que dentro do textbox tenha os beneficiarios em ordem de nascimento.E é isso que está me deixando nervosa
rsrsrsr
-
Olá tudo bem quando vc faz ordenado recebe sua listaOrdenado sua variavel ordenado já contém todos os seus dados ordenados pela data de nascimento, basta iterar pela lista de ordenado para jogar os dados nas textbox e mostrar os dados como quer tipo assim :
For Each item in ordenado Text += "Responsavel " & item.Nome & newVbLine & 'assim continua igual faz...
Veja se consegue.. Não precisa ficar nervosa rs.
- Marcado como Resposta Giovani Cr segunda-feira, 7 de abril de 2014 20:20