Usuário com melhor resposta
GridView_SelectedIndexChanged

Pergunta
-
Em um WebAplication tenho em um TabContainer com um GridView que ao selecionar uma linha deveria estar carregando os campos do Form, mas aparece a mensagem abaixo logo na primeira linha de código:
If gvwPJ.SelectedRow.Cells(2).Text = "" Then
rblCategoriaCadastro.ClearSelection()
ElseIf gvwPJ.SelectedRow.Cells(2).Text = "Endereço" Then
rblCategoriaCadastro.SelectedIndex = 0
ElseIf gvwPJ.SelectedRow.Cells(2).Text = "Pessoa Jurídica" Then
rblCategoriaCadastro.SelectedIndex = 1
ElseIf gvwPJ.SelectedRow.Cells(2).Text = "Pessoa Física" Then
rblCategoriaCadastro.SelectedIndex = 2
End Ifa mensagem:
O índice estava fora do intervalo. Ele deve ser não-negativo e menor que o tamanho da coleção.
Nome do parâmetro: index
Respostas
-
Resolvido abaixo (De: Para:), obrigado Junior e Cleber.
''' <summary>
''' Direciona para cada View conforme as categorias de cadastro: Endereço, Pessoa Jurídica ou Pessoa Física
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles rblCategoriaCadastro.SelectedIndexChanged
btnInserir.Enabled = True
btnPesquisar.Enabled = True
txtPesquisa.Enabled = True
If rblCategoriaCadastro.SelectedIndex = 0 Then
mtvCadastro.ActiveViewIndex = 0
ElseIf rblCategoriaCadastro.SelectedIndex = 1 Then
mtvCadastro.ActiveViewIndex = 1
TabContainerPJ.ActiveTabIndex = 0
CargaddlPJEnd()
CargaddlPJEnd0()
CargaddlPJEnd1()
ElseIf rblCategoriaCadastro.SelectedIndex = 2 Then
mtvCadastro.ActiveViewIndex = 4
TabContainerPF.ActiveTabIndex = 0
CargaddlPFEnd()
End If
End SubDe:
Protected Sub TabContainerPJ_ActiveTabChanged(sender As Object, e As EventArgs) Handles TabContainerPJ.ActiveTabChanged
If TabContainerPJ.ActiveTabIndex = 0 Then
gvwPJ.DataSource = Nothing
gvwPJ.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 1 Then
gvwUA.DataSource = Nothing
gvwUA.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 2 Then
gvwUS.DataSource = Nothing
gvwUS.DataBind()
End If
End SubPara:
Protected Sub TabContainerPJ_ActiveTabChanged(sender As Object, e As EventArgs) Handles TabContainerPJ.ActiveTabChanged
If TabContainerPJ.ActiveTabIndex = 0 Then
' gvwPJ.DataSource = Nothing
' gvwPJ.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 1 Then
' gvwUA.DataSource = Nothing
' gvwUA.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 2 Then
' gvwUS.DataSource = Nothing
' gvwUS.DataBind()
End If
End Sub- Marcado como Resposta Wilson Boris terça-feira, 5 de junho de 2012 14:45
Todas as Respostas
-
-
-
-
-
-
Junior, muito obrigado pelo retorno, o meu select abaixo:
ElseIf mtvCadastro.ActiveViewIndex = 1 Then
If TabContainerPJ.ActiveTabIndex = 0 Then
comando.CommandText = "SELECT * FROM tbCadPessoaJuridica WHERE razaoSocial LIKE '%" + txtRazao.Text + "%' ORDER BY codRazaoSocial DESC"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwPJ.DataSource = dr
gvwPJ.DataBind()
dr.Close()
End Using
con.Close() -
Wilson, uma recomendação, qdo se programa para web a melhor prática é evitar select * from, pois se sua tabela tiver muitas colunas na sua consulta ele trará todas as colunas e só depois fará o filtro para as colunas que vc quer, então se sua tabela tem muitos registros e muitas colunas sua página pode ficar lenta para carregar.
Altere seu select somente para as colunas que vc vai usar e as colunas onde no banco tem aceita nulos vc faz assim :
select isnull(seucampo,'valorPadrao') as seucampo,isnull(seucampo1,'valorpadrao') as seucampo1,seucampo3 from tabela
Lembrando que o 'ValorPadrao' será jogado no result do seu select ai vc pode colocar 'um valor numérico' ou 'uma string' exemplo : '1' ou '' .
Assim seu result para esses campos não trará mais NULL
Junior
-
Junior, não sei se tem sentido o meu raciocínio, mas estou fazendo o select *, pois todos os campos da tabela eu tenho no form e utilizo o botão select do grid para esse carregamendo para possibilitar alterações ou exclusões de registros da tabela, caso contrário, como faria o carregamento destes campos?
-
Wilson como vc esta fazendo o select * vc não está tratando nenhum campo especificamente ou seja, os campos na tabela que permitem NULL vc está trazendo do jeito que ele está no banco ou seja NULL, ai qdo vc vai carregar a informação para o gridview dá erro, não tem outra maneira no select vc tem que tratar esses campos como te falei a clásula isnull no sql trata os campos que permitem nulos assim caso o campo esteja nulo vc coloca um valor padrão para ele, is null(seucampo,'valorpadrao') as nome, veja exemplo
isnull(dataalteracao,'01/01/2000') as dataalteracao
entendeu ?
Junior
-
Junior abaixo a implementação no select, seria isto? Porém, o problema continua. Quando voce comentou: "ai qdo vc vai carregar a informação para o gridview dá erro", não sei se estou entendendo, mas o fato é que o GRID eu carrego normalmente, o problema ocorre quando clico no SELECT do GRID "SelectedIndexChanged" para carregar os campos do Form na necessidade de fazer uma alteração ou exclusão de um registro.
Dim con As New OleDbConnection
con.ConnectionString = My.Settings.SIADSConecte
Dim comando As New OleDbCommand
comando.Connection = con
'comando.CommandText = "SELECT * FROM tbCadPessoaJuridica WHERE razaoSocial LIKE '%" + txtRazao.Text + "%' ORDER BY codRazaoSocial DESC"
comando.CommandText = "select isnull(categoriaPJ,'categoriaPJ') as categoriaPJ,isnull(dataCadastro,'dataCadastro') as dataCadastro,isnull(razaoSocial,'razaoSocial') as razaoSocial,isnull(nomeFant,'nomeFant') as nomeFant,isnull(socioProp,'socioProp') as socioProp,isnull(cpf,'cpf') as cpf,isnull(dataFundacao,'dataFundacao') as dataFundacao,isnull(cnpj,'cnpj') as cnpj,isnull(ie,'ie') as ie,isnull(dtInCont,'dtInCont') as dtInCont,isnull(dtTerCont,'dtTerCont') as dtTerCont,isnull(codCnae,'codCnae') as codCnae,isnull(codEndPJ,'codEndPJ') as codEndPJ,isnull(observacao,'observacao') as observacao, from tbCadPessoaJuridica WHERE razaoSocial LIKE '%" + txtRazao.Text + "%' ORDER BY codRazaoSocial DESC"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwPJ.DataSource = dr
gvwPJ.DataBind()
dr.Close()
End Using
con.Close() -
execute o select no query analiser e veja o resultado, se mesmo assim está dando erro pode ser isso aqui
gvwPJ.SelectedRow.Cells(2).
será que vc tem o cells(2) no seu gridview ?
Portanto ai é para esse if acontecer na terceira coluna do seu gridview.
Lembre-se que o índice no gridview começa de 0, veja qtas colunas vc tem no seu gridview.
Junior
-
Junior, como posso executar o select no query analiser.
Ao fazer um Breakpoint em Protected Sub gvwPJ_SelectedIndexChanged e ao passar o mouse sobre a linha a unica informação que aparece é sobre o grid "{System.Web.UI.WebControls.GridView}", neste clicando em "Cells" no + o valor do "Count" esta em "0".
-
Junior, como posso executar o select no query analiser.
Ao fazer um Breakpoint em Protected Sub gvwPJ_SelectedIndexChanged e ao passar o mouse sobre a linha a unica informação que aparece é sobre o grid "{System.Web.UI.WebControls.GridView}", neste clicando em "Cells" no + o valor do "Count" esta em "0".
Veja, o GRID esta sendo montado, sem problemas. -
Resolvido abaixo (De: Para:), obrigado Junior e Cleber.
''' <summary>
''' Direciona para cada View conforme as categorias de cadastro: Endereço, Pessoa Jurídica ou Pessoa Física
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Protected Sub RadioButtonList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles rblCategoriaCadastro.SelectedIndexChanged
btnInserir.Enabled = True
btnPesquisar.Enabled = True
txtPesquisa.Enabled = True
If rblCategoriaCadastro.SelectedIndex = 0 Then
mtvCadastro.ActiveViewIndex = 0
ElseIf rblCategoriaCadastro.SelectedIndex = 1 Then
mtvCadastro.ActiveViewIndex = 1
TabContainerPJ.ActiveTabIndex = 0
CargaddlPJEnd()
CargaddlPJEnd0()
CargaddlPJEnd1()
ElseIf rblCategoriaCadastro.SelectedIndex = 2 Then
mtvCadastro.ActiveViewIndex = 4
TabContainerPF.ActiveTabIndex = 0
CargaddlPFEnd()
End If
End SubDe:
Protected Sub TabContainerPJ_ActiveTabChanged(sender As Object, e As EventArgs) Handles TabContainerPJ.ActiveTabChanged
If TabContainerPJ.ActiveTabIndex = 0 Then
gvwPJ.DataSource = Nothing
gvwPJ.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 1 Then
gvwUA.DataSource = Nothing
gvwUA.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 2 Then
gvwUS.DataSource = Nothing
gvwUS.DataBind()
End If
End SubPara:
Protected Sub TabContainerPJ_ActiveTabChanged(sender As Object, e As EventArgs) Handles TabContainerPJ.ActiveTabChanged
If TabContainerPJ.ActiveTabIndex = 0 Then
' gvwPJ.DataSource = Nothing
' gvwPJ.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 1 Then
' gvwUA.DataSource = Nothing
' gvwUA.DataBind()
ElseIf TabContainerPJ.ActiveTabIndex = 2 Then
' gvwUS.DataSource = Nothing
' gvwUS.DataBind()
End If
End Sub- Marcado como Resposta Wilson Boris terça-feira, 5 de junho de 2012 14:45