SapoBelgas Posted June 3, 2008 at 02:54 PM Report Share #189334 Posted June 3, 2008 at 02:54 PM boas... a minha duvida e adicionar directamente registo de uma label num datagridview em base de dados. passo a explicar, o meu programa e tipo totolo, e o meu objectivo e que ao cilcar num botao, o resultado que obitive, neste caso se tive ou nao premio, aparecer no Datagridview, mas sempre que clicar outra vez no botao, adicione em baixo do que ja la estava o novo resultado. mas no meu caso nao sou eu que crio o que se vai inserir, eu fiz um trabalho que era um lista telefonica, eu colocava o nome, telefone, ect e depois inseria na base de dados, no trabalho que tou a fazer agora nao e assim... ao clicar no botao, e calculado entre 2 vectores os numeros que estao iguais e dependendo do numero da um premio. o que eu tenho que inserir no Datagridview e o numero da tentativa ( que deve ser qualquer coiso + 1 [chave primaria]) e que premio teve nessa tentativa... como e que devo fazer??? Link to comment Share on other sites More sharing options...
jpaulino Posted June 3, 2008 at 05:08 PM Report Share #189366 Posted June 3, 2008 at 05:08 PM Mostra lá uma imagem do que tens porque não estou a entender! Link to comment Share on other sites More sharing options...
SapoBelgas Posted June 3, 2008 at 07:14 PM Author Report Share #189392 Posted June 3, 2008 at 07:14 PM http://img58.imageshack.us/img58/1056/semttulooz2.th.png bem e isto... preenche se as txtbox com um numero, ao clicar em apostar esses numeros sao verificados com os numeros que vem nas labels (e um vector) e depois dependendo da quantidade que acertou, tem o premio X. e é esse resultado que tenho que meter no Datagridview. o NumTentativa é sempre +1, o NumPremios tem que ser o valor que vai aparecer em Premio... o menu de navegaçao ainda nao ta a funcionar, mas ando a tratar dixo... preciso faxer kom k ao ciclar seguinte ele mostre o resultado seguinte. ta bom, ou queres k poste o trabalho?? Link to comment Share on other sites More sharing options...
jpaulino Posted June 4, 2008 at 08:17 PM Report Share #189535 Posted June 4, 2008 at 08:17 PM Desculpa a ausência ... E a datagridview não está ligada a nada, certo ? Link to comment Share on other sites More sharing options...
SapoBelgas Posted June 4, 2008 at 08:37 PM Author Report Share #189542 Posted June 4, 2008 at 08:37 PM yap... eu reparei nma koisa... da maneira k estou a faxer, n tou a usar a base de dados... lool... mas desd que funcione.. lol... nepx, n ta ligado a nada... Link to comment Share on other sites More sharing options...
jpaulino Posted June 4, 2008 at 08:40 PM Report Share #189545 Posted June 4, 2008 at 08:40 PM Então mas precisas de estar ligado a uma base de dados ? Se precisares vê aqui um exemplo que é muito simples: VB.NET: Utilizando o controlo DataGridView http://vbtuga.blogspot.com/2008/04/vbnet-utilizando-o-controlo.html É que se tive ligado o código é muito diferente! Link to comment Share on other sites More sharing options...
SapoBelgas Posted June 5, 2008 at 11:48 AM Author Report Share #189620 Posted June 5, 2008 at 11:48 AM nao, nao esta ligada a uma base de dados... apenas e para mostrar os valores.. tipo no site que deste encontrei la isto. Private Sub btnGravar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGravar.Click ' Cria automáticamente o comando para permite actualizar a DataSet Dim cb As New SqlCommandBuilder(da) ' Actualiza na DataSet, e por sua vez na tabela, as alterações efectadas da.Update(ds, "myTable") End Sub mas a base de dados esta em SQL Server e eu n sei komo passar para Acess komo e k fica isto? Dim cb As New SqlCommandBuilder(da) (isto e para outro trabalho) Link to comment Share on other sites More sharing options...
jpaulino Posted June 5, 2008 at 11:54 AM Report Share #189621 Posted June 5, 2008 at 11:54 AM "Neste caso será utilizado o SQL Server mas o exemplo também se aplica ao Microsoft Access, alterando apenas para as suas classes." Ou seja apenas tens de substituir o Sql por OLEDB em todo o lado. Ex: Dim cb As New SqlCommandBuilder fica Dim cb As New OledbCommandBuilder Link to comment Share on other sites More sharing options...
SapoBelgas Posted June 5, 2008 at 05:27 PM Author Report Share #189658 Posted June 5, 2008 at 05:27 PM pois... mas eu ja tentei ixo e nao deu.. deu m erro no "da" nao sei poque.. eu delarei a variavel. Link to comment Share on other sites More sharing options...
jpaulino Posted June 5, 2008 at 05:32 PM Report Share #189659 Posted June 5, 2008 at 05:32 PM Sim e fizeste o imports Imports System.Data.OleDb Link to comment Share on other sites More sharing options...
SapoBelgas Posted June 5, 2008 at 07:48 PM Author Report Share #189686 Posted June 5, 2008 at 07:48 PM e axim. isto e o que eu tenho de um trabalho da eskola... Public Class frmPrincipal Dim StrConn As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\BDContactos.mdb" Dim Conn As New OleDb.OleDbConnection Dim da As New OleDb.OleDbDataAdapter Dim ds As New DataSet Dim txtSQL As String Dim cmd As New OleDb.OleDbCommand Dim TotalReg As Integer Dim RegActual As Integer Private Sub frmPrincipal_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Conn.ConnectionString = StrConn Try Conn.Open() txtSQL = "Select * From Contactos" da = New OleDb.OleDbDataAdapter(txtSQL, Conn) Conn.Close() da.Fill(ds, "TodosContactos") TotalReg = ds.Tables("TodosContactos").Rows.Count() If TotalReg = 0 Then RegActual = 0 Else RegActual = 1 End If DataGridView.DataSource = ds.Tables("TodosContactos") DataGridView.ReadOnly = True DataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect Actualizar_Navegador(RegActual, TotalReg) Actualizar_Detalhe(RegActual) lblStatus.Text = "Consultar" Catch ex As Exception MsgBox("ERRO " & ex.Message, MsgBoxStyle.Critical, "Erro") End Try End Sub Sub Actualizar_Navegador(ByVal Pos As Integer, ByVal TotalReg As Integer) lblPainel.Text = RegActual.ToString & " de " & TotalReg.ToString btnPrimeiro.Enabled = True btnAnterior.Enabled = True btnUltimo.Enabled = True btnProximo.Enabled = True If RegActual <= 1 Then btnPrimeiro.Enabled = False btnAnterior.Enabled = False End If If RegActual >= TotalReg Then btnUltimo.Enabled = False btnProximo.Enabled = False End If End Sub Sub Actualizar_Detalhe(ByVal Pos As Integer) Dim dr As DataRow If Pos = 0 Then nudCod.Value = 0 txtNome.Text = "" txtLocal.Text = "" txtTel.Text = "" chkVip.CheckState = CheckState.Indeterminate Else dr = ds.Tables("TodosContactos").Rows(Pos - 1) txtNome.Text = dr.Item("Nome").ToString txtLocal.Text = dr.Item("Localidade").ToString txtTel.Text = dr.Item("Telefone").ToString nudCod.Value = dr.Item("CodContacto") If dr.Item("VIP") Then chkVip.CheckState = CheckState.Checked Else chkVip.CheckState = CheckState.Unchecked End If DataGridView.Rows(Pos - 1).Selected = True End If End Sub Private Sub btnProximo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnProximo.Click If RegActual < TotalReg Then RegActual = RegActual + 1 End If Actualizar_Detalhe(RegActual) Actualizar_Navegador(RegActual, TotalReg) lblStatus.Text = "Consultar" End Sub Private Sub btnAnterior_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAnterior.Click If RegActual > 0 Then RegActual = RegActual - 1 End If Actualizar_Detalhe(RegActual) Actualizar_Navegador(RegActual, TotalReg) lblStatus.Text = "Consultar" End Sub Private Sub btnPrimeiro_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrimeiro.Click RegActual = 1 Actualizar_Detalhe(RegActual) Actualizar_Navegador(RegActual, TotalReg) lblStatus.Text = "Consultar" End Sub Private Sub btnUltimo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUltimo.Click RegActual = TotalReg Actualizar_Detalhe(RegActual) Actualizar_Navegador(RegActual, TotalReg) lblStatus.Text = "Consultar" End Sub Private Sub btnEleminar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEleminar.Click Dim Resp As Integer Dim cod As Integer cod = nudCod.Value Resp = MsgBox("Eleminar o registo com o código " & cod & "?", MsgBoxStyle.Exclamation + MsgBoxStyle.YesNo, "Comfirmação") If Resp = MsgBoxResult.Yes Then txtSQL = "Delete * From Contactos where codContacto = " & cod Conn.Open() cmd.Connection = Conn cmd.CommandText = txtSQL cmd.ExecuteNonQuery() Conn.Close() ds.Clear() da.Fill(ds, "TodosContactos") DataGridView.Update() If RegActual > 1 Then RegActual = RegActual - 1 End If TotalReg = ds.Tables("TodosContactos").Rows.Count() If TotalReg = 0 Then RegActual = 0 End If Actualizar_Navegador(RegActual, TotalReg) Actualizar_Detalhe(RegActual) End If End Sub Private Sub DataGridView_CellClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView.CellClick 'este procedimento so funciona se a ordem for = a False ' RegActual = DataGridView.SelectedRows(0).Index - 1 ' Actualizar_Navegador(RegActual, TotalReg) ' Actualizar_Detalhe(RegActual) End Sub Private Sub btnAdicionar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdicionar.Click Dim resp As Integer Dim cod As Integer cod = nudCod.Value resp = MsgBox("Inserir contacto com o codigo " & cod & "?", MsgBoxStyle.Question + MsgBoxStyle.YesNo, "Confirmar") If resp = MsgBoxResult.Yes Then txtSQL = "insert into contactos(nome,localidade,telefone,codContacto,vip) VALUES(""" & txtNome.Text & """,""" & txtLocal.Text & """,""" & txtTel.Text & """,""" & nudCod.Value & """,""" & chkVip.CheckState & """)" Conn.Open() cmd.Connection = Conn cmd.CommandText = txtSQL cmd.ExecuteNonQuery() Conn.Close() ds.Clear() da.Fill(ds, "TodosContactos") DataGridView.Update() TotalReg = ds.Tables("TodosContactos").Rows.Count() RegActual = TotalReg End If End Sub End Class mas o adicionar n esta a dar bem, tenho que arranjar uma maneira de verificar se o registo ja existe e n sei komo... mas eu comecei a fazer um novo doutra forma... (o que tenho aprendido aqui) mas ainda faltam coisas.... mas com isto tudo nao consegui arranjar o que queria mesmo. que era o que queria no inicio, arranar uma forma de o valor que tenho, meto lo na DGV. que é um "registo" que tenho numa label. isto: lblPremios.Text = "Ganhou o " & Resultado & "º premio!" Resultado é uma variavel. por exemplo, "Ganhou o 3º premio" tenho que meter isto no DGV.. da para fazer??? ps: dcp isto ser muito grande... lol Link to comment Share on other sites More sharing options...
jpaulino Posted June 5, 2008 at 09:18 PM Report Share #189694 Posted June 5, 2008 at 09:18 PM Olá, Duas ou três coisinhas: 1 - Para inserires registos de uma forma fácil e mais eficaz utilizas os parameters. Podes ver em: VB.NET: Gestão de Dados em SQL Server - Parte I http://vbtuga.blogspot.com/2008/04/vbnet-gesto-de-dados-em-sql-server.html 2 - Qual é o erro que dá, o que é que não faz, etc ? Explica lá melhor! 3 - Para verificares se o registo existe ou não podes utilizar o ExecuteScalar() caso tenhas de fazer uma consulta à base de dados. Pode ver em: VB.NET: Gestão de Dados em SQL Server - Parte II http://vbtuga.blogspot.com/2008/04/vbnet-gesto-de-dados-em-sql-server_16.html Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now