Inquiridor
Gridview não carrega o registro incluido

Pergunta
-
Alguém tem alguma sugestão?
Nas linhas abaixo ao inserir um registro e gravar o Gridview não mostra o seu conteúdo. Porém, ao clicar no botão Pesquisar o registro é carregado.
Private Sub cargaGRID()
Dim con As New OleDbConnection
con.ConnectionString = My.Settings.SIADSConecte
Dim comando As New OleDbCommand
comando.Connection = con
comando.CommandText = "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtPesquisa.Text + "%' ORDER BY codendereco DESC"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwEnd.DataSource = dr
gvwEnd.DataBind()
dr.Close()
End Using
con.Close()txtCodEnd.Text = gvwEnd.Rows(0).Cells(1).Text
Session.Add("Código do Endereço", txtCodEnd.Text)
End SubProtected Sub Button6_Click(sender As Object, e As EventArgs) Handles btnPesquisar.Click
cargaGRID()
End Sub
Protected Sub gvwEnd_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvwEnd.RowDataBound
If e.Row.RowType = DataControlRowType.Header Then
e.Row.Cells(1).Visible = False
e.Row.Cells(2).Visible = False
e.Row.Cells(3).Visible = False
e.Row.Cells(4).Visible = False
e.Row.Cells(5).Text = "Logradouro"
e.Row.Cells(6).Text = "Número"
e.Row.Cells(7).Visible = False
e.Row.Cells(8).Visible = False
e.Row.Cells(9).Visible = False
e.Row.Cells(10).Visible = False
e.Row.Cells(11).Text = "Tel. celular"
e.Row.Cells(12).Visible = False
e.Row.Cells(13).Visible = False
e.Row.Cells(14).Visible = False
e.Row.Cells(15).Visible = False
e.Row.Cells(16).Text = "Nome contato"
e.Row.Cells(17).Visible = False
e.Row.Cells(18).Visible = False
End If
If e.Row.RowType = DataControlRowType.DataRow Then
e.Row.Cells(1).Visible = True
e.Row.Cells(2).Visible = False
e.Row.Cells(3).Visible = False
e.Row.Cells(4).Visible = False
e.Row.Cells(5).Visible = True
e.Row.Cells(6).Visible = True
e.Row.Cells(7).Visible = False
e.Row.Cells(8).Visible = False
e.Row.Cells(9).Visible = False
e.Row.Cells(10).Visible = False
e.Row.Cells(11).Visible = True
e.Row.Cells(12).Visible = False
e.Row.Cells(13).Visible = False
e.Row.Cells(14).Visible = False
e.Row.Cells(15).Visible = False
e.Row.Cells(16).Visible = True
e.Row.Cells(17).Visible = False
e.Row.Cells(18).Visible = False
End If
End SubPrivate Sub habilita()
rblCategoria.Enabled = True
ddlUnidAdm.Enabled = False
rblTipo.Enabled = True
txtLogra.Enabled = True
txtNum.Enabled = True
rblSituacao.Enabled = True
txtBairroLocal.Enabled = True
txtTelRes.Enabled = True
txtTelCom.Enabled = True
txtTelCel.Enabled = True
ddlUF.Enabled = True
ddlMun.Enabled = True
txtEmail.Enabled = True
txtHome.Enabled = True
txtContato.Enabled = True
rblCondiAtual.Enabled = True
txtObserva.Enabled = True
'.....
btnInserir.Enabled = False
btnAlterar.Enabled = False
btnExcluir.Enabled = False
btnGravar.Enabled = True
btnCancelar.Enabled = True
End SubProtected Sub Button1_Click(sender As Object, e As EventArgs) Handles btnInserir.Click
limpa()
habilita()
modo.Text = "I"
rblCategoria.Focus()
End SubPrivate Sub inserir()
Dim conecte As New OleDbConnection
conecte.ConnectionString = My.Settings.SIADSConecte
Try
conecte.Open()
Catch ex As System.Data.OleDb.OleDbException
Label1.Text = "Erro de conexao com o Banco de Dados: " & ex.Message.ToString
Return
End Try
Dim selcom As New System.Data.OleDb.OleDbCommand
selcom.Connection = conecte
selcom.CommandText = "INSERT INTO tbCadEndereco ( categoria,unidadeadministrativa,tipo,logradouro,numero,situacao,bairro,telRes,telCom,telCel,estado,municipio,email,site,nomecontato,ativo,observacoes)" & _
" VALUES('" & rblCategoria.Text & "' ,'" & ddlUnidAdm.Text & "','" & rblTipo.Text & "','" & txtLogra.Text & "','" & txtNum.Text & "','" & rblSituacao.Text & "','" & txtBairroLocal.Text & "','" & txtTelRes.Text & "','" & txtTelCom.Text & "','" & txtTelCel.Text & "','" & ddlUF.Text & "','" & ddlMun.Text & "','" & txtEmail.Text & "','" & txtHome.Text & "','" & txtContato.Text & "','" & rblCondiAtual.Text & "','" & txtObserva.Text & "')"
Dim teste As Boolean
Try
teste = selcom.ExecuteNonQuery
Catch ex As System.Data.OleDb.OleDbException
Label1.Text = "Erro: " & ex.Message.ToString
Return
End Try
Label1.Text = "Dados gravados com sucesso"
desabilita()
txtPesquisa.Text = ""
cargaGRID()
End SubProtected Sub Button4_Click(sender As Object, e As EventArgs) Handles btnGravar.Click
If modo.Text = "A" Then
alterar()
modo.Text = ""
End If
If modo.Text = "I" Then
inserir()
Redireciona()
End If
If modo.Text = "E" Then
excluir()
End If
modo.Text = "X"
End Sub
Todas as Respostas
-
-
Antes de qualquer coisa, obrigado pelo retorno.
O que estou pretendendo é ao clicar no botão inserir todos os campos fiquem limpos e habilitados, na sequencia ele entra no modo "I" e faz a conexão com o BD instruido pelo comando INSERT e posteriormente carrega o GRID. Quanto a sua pergunta eu penso que sim.
-
Wilson lembre-se que web trabalhamos desconectados, a gridview serve basicamente para mostrar dados, informações, se vc quer que ela atualize depois de um insert vc deve sempre depois de inserir um registro no banco carregar a grid no seu caso é vc chamar o cargaGrid(), lembrando que caso sua grid traga muitos registros verifique se isso é realmente necessário, pois sua página pode ficar lenta já que sempre carregará o gridview com muitos dados.
Junior
-
-
-
-
webform não trabalhamos com dados conectados pois toda a ação se dá no servidor web, os dados só sao atualizados qdo vai pro servidor e volta, tipo um clique de um botão ai toda a página é renderizada e assim os dados são atualizados, diferentes do windows forms que existe como se fosse uma ligação entre sua aplicação e o banco de dados assim os dados são sempre atualizados.
Por isso se vc quer que apareça na sua grid o registro inserido vc tem que carrega-lo logo após a inserção do registro, assim a página vai no servidor é renderizada e a grid é preenchida com os dados do banco ai seu registro vai aparecer, entendeu ?
Junior
-
-
-
-
pq o seu cargaGRID() o select dele está vinculado ao txtpesquisa note
comando.CommandText = "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtPesquisa.Text + "%' ORDER BY codendereco DESC"
então vc faz a inclusão e o txtpesquisa.text naõ tem nada ai ele não tras tira isso do teu select que vai dar certo e faz um somente qdo vc for trazer algo da pesquisa
Junior
-
Luiz, tá estranho!
Veja: Primeiro, eu fiz um cargaGRID exclusivo para o botão pesquisa("SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtPesquisa.Text + "%' ORDER BY codendereco DESC"). Segundo, após a instrução INSERT eu chamo outro carregaGRID com o seguinte "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtLogra.Text + "%'". O fato é que se eu faço um BreakPoint, no Grid aparece o novo registro, porém se não faço o BreakPoint apenas aparece a mensagem "Dados gravados com sucesso"
-
-
Ok, eu fiz estas alteraçoes pelo meu entendimento no percurso. Abaixo um trecho do form:
Private Sub cargaGRID()
Dim con As New OleDbConnection
con.ConnectionString = My.Settings.SIADSConecte
Dim comando As New OleDbCommand
comando.Connection = con
comando.CommandText = "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtLogra.Text + "%'"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwEnd.DataSource = dr
gvwEnd.DataBind()
dr.Close()
End Using
con.Close()
End SubProtected Sub Button6_Click(sender As Object, e As EventArgs) Handles btnPesquisar.Click
Dim con As New OleDbConnection
con.ConnectionString = My.Settings.SIADSConecte
Dim comando As New OleDbCommand
comando.Connection = con
comando.CommandText = "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtPesquisa.Text + "%' ORDER BY codendereco DESC"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwEnd.DataSource = dr
gvwEnd.DataBind()
dr.Close()
End Using
con.Close()
End SubProtected Sub Button1_Click(sender As Object, e As EventArgs) Handles btnInserir.Click
limpa()
habilita()
modo.Text = "I"
rblCategoria.Focus()
End SubPrivate Sub inserir()
Dim conecte As New OleDbConnection
conecte.ConnectionString = My.Settings.SIADSConecte
Try
conecte.Open()
Catch ex As System.Data.OleDb.OleDbException
Label1.Text = "Erro de conexao com o Banco de Dados: " & ex.Message.ToString
Return
End Try
Dim selcom As New System.Data.OleDb.OleDbCommand
selcom.Connection = conecte
selcom.CommandText = "INSERT INTO tbCadEndereco ( categoria,unidadeadministrativa,tipo,logradouro,numero,situacao,bairro,telRes,telCom,telCel,estado,municipio,email,site,nomecontato,ativo,observacoes)" & _
" VALUES('" & rblCategoria.Text & "' ,'" & ddlUnidAdm.Text & "','" & rblTipo.Text & "','" & txtLogra.Text & "','" & txtNum.Text & "','" & rblSituacao.Text & "','" & txtBairroLocal.Text & "','" & txtTelRes.Text & "','" & txtTelCom.Text & "','" & txtTelCel.Text & "','" & ddlUF.Text & "','" & ddlMun.Text & "','" & txtEmail.Text & "','" & txtHome.Text & "','" & txtContato.Text & "','" & rblCondiAtual.Text & "','" & txtObserva.Text & "')"
Dim teste As Boolean
Try
teste = selcom.ExecuteNonQuery
Catch ex As System.Data.OleDb.OleDbException
Label1.Text = "Erro: " & ex.Message.ToString
Return
End Try
Label1.Text = "Dados gravados com sucesso"cargaGRID()
desabilita()End Sub
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles btnAlterar.Click
habilita()
modo.Text = "A"
End SubProtected Sub Button3_Click(sender As Object, e As EventArgs) Handles btnExcluir.Click
habilita()
modo.Text = "E"
End SubProtected Sub Button5_Click(sender As Object, e As EventArgs) Handles btnCancelar.Click
desabilita()
limpa()
modo.Text = ""
End Sub
Protected Sub Button4_Click(sender As Object, e As EventArgs) Handles btnGravar.Click
If modo.Text = "A" Then
alterar()
redireciona()
modo.Text = ""
End If
If modo.Text = "I" Then
inserir()
' redireciona()
End If
If modo.Text = "E" Then
excluir()
End If
modo.Text = "X"
End Sub -
Wilson debuga direitinho para ver se depois da inserção ele não está executando algo depois do cargagrid() pq tem o evento do button6 que carrega a grid diferente, ai só vc debugando para ver onde ele passa, não tem sentido ele não carregar a grid vc deve estar carregando esse grid de duas maneiras diferentes.
Junior
-
Luis,
debugando a partir da linha Private Sub inserir()
Private Sub cargaGRID()
Protected Sub gwv_RowDataBound
Private Sub desabilita()
e carrega o Form "Dados gravados com sucesso" e o novo registro no GrigObs.: sem debugar: "dados gravados com sucesso" e Grid não carrega nada
-
Luis,
debugando a partir da linha Private Sub inserir()
Private Sub cargaGRID()
Protected Sub gwv_RowDataBound
Private Sub desabilita()
e carrega o Form "Dados gravados com sucesso" e o novo registro no GrigObs.: sem debugar: "dados gravados com sucesso" e Grid não carrega nada
Quer que eu post todas as linhas?
- Editado Wilson Boris terça-feira, 15 de maio de 2012 20:44
-
Wilson não tem pq no debug ele mostrar algo e sem debugar ele não mostra, como te falei veja os passos tb vc não esteja debugando tudo, ai ele para e vc não ver o carregamendo do gridview novamente coisa que sem debugar ele passa e fica na ultima posição, entendeu ?
Junior
-
Luis,
debugando a partir da linha Private Sub inserir()
Private Sub cargaGRID()
Protected Sub gwv_RowDataBound
Private Sub desabilita()
e carrega o Form "Dados gravados com sucesso" e o novo registro no GrigObs.: sem debugar: "dados gravados com sucesso" e Grid não carrega nada
Quer que eu post todas as linhas?
Não esqueça de usar o componente </> na barra para posta seu código. Microsoft MCPD,MCTS,MCC
-
Ainda não estou usando, mas pretendo....
Abaixo algumas linhas da situação atual html:
Resumindo eu centralizei a div usei um Panel e nele usei uma Tabela onde inseri um WebUserControl e para os botões eu inseri uma nova Tabela na sequência os demais comandos Textbox, label, radiobutonlist, dropdownlist e o grid.
/head>
<body>
<form id="form1" runat="server">
<div>
<center>
<asp:Panel ID="Panel1" runat="server" Height="835px" Width="950px">
<table class="style1">
<tr>
<td class="style6" colspan="3">
<uc1:WebUserControlSIADSmenu ID="WebUserControlSIADSmenu1" runat="server" />
</td>
</tr>
<tr>
<td class="style18" colspan="3">
<table class="style22">
<tr>
<td class="style25" colspan="3" style="text-align: left">
<strong>CADASTRO ENDEREÇO</strong></td>
</tr>
<tr>
<td style="text-align: left">
<asp:Button ID="btnInserir" runat="server" Height="30px" Text="Inserir"
Width="70px" />
<asp:Button ID="btnAlterar" runat="server" Height="30px" Text="Alterar"
Width="70px" />
<asp:Button ID="btnExcluir" runat="server" Height="30px" Text="Excluir"
Width="70px" />
</td>
<td style="text-align: left">
<asp:Button ID="btnGravar" runat="server" Height="30px" Text="Gravar"
Width="70px" />
<asp:Button ID="btnCancelar" runat="server" Height="30px" Text="Cancelar"
Width="70px" />
</td>
<td style="text-align: right">
<asp:TextBox ID="txtPesquisa" runat="server" style="margin-right: 0px"
Width="280px" BackColor="#E1E1E1"></asp:TextBox>
<asp:Button ID="btnPesquisar" runat="server" Height="30px" Text="Pesquisar"
Width="70px" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td class="style18" style="text-align: left">
</td>
<td class="style14">
</td>
<td class="style23">
</td>
</tr>
<tr>
<td class="style18" style="text-align: left">
Categoria: <asp:Label ID="LabelCategoria" runat="server" style="color: #808080"></asp:Label>
<asp:RadioButtonList ID="rblCategoria" runat="server" Width="285px"
BackColor="#E1E1E1" RepeatColumns="2" AutoPostBack="True"
style="color: #333333">
</asp:RadioButtonList>
</td>
RESTANTE DOS COMANDOS TEXT, DROPDOWNLIST E RADIOBUTTON<td class="style18" colspan="3" style="text-align: left">
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:GridView ID="gvwEnd" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ButtonType="Button" SelectText="Selecionar"
ShowSelectButton="True" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>
</td>
</tr>
</table>
</asp:Panel>
</center>
</div>
</form>
</body>
</html> -
Para esclarecer mais um pouco... inclui uma variavel de sessão para captar o novo código de endereço e ao debugar tudo ocorre normalmente, mas se não degugar aparece a mensagem conforme a linha: 'com o BreakPoint na Sub:
Private Sub cargaGRID()
Dim con As New OleDbConnection
con.ConnectionString = My.Settings.SIADSConecte
Dim comando As New OleDbCommand
comando.Connection = con
comando.CommandText = "SELECT * FROM tbCadEndereco WHERE logradouro LIKE '%" + txtLogra.Text + "%'"
If Not con.State = ConnectionState.Open Then
con.Open()
End If
Using dr As OleDbDataReader = comando.ExecuteReader
gvwEnd.DataSource = dr
gvwEnd.DataBind()
dr.Close()
End Using
con.Close()
lblCodEnd.Text = gvwEnd.Rows(0).Cells(1).Text
'com o BreakPoint na Sub: 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
Session.Add("Código do Endereço", lblCodEnd.Text)
End Sub