Home Page
Articoli
Tips & Tricks
News
Forum
Archivio Forum
Blogs
Sondaggi
Rss
Video
Utenti
Chi Siamo
Contattaci
Username:
Password:
Login
Registrati ora!
Recupera Password
Home Page
Stanze Forum
App. WinForms / WPF .NET
Percorso database da codice in visual studio 2005
martedì 12 agosto 2008 - 11.32
Elenco Threads
Stanze Forum
Aggiungi ai Preferiti
Cerca nel forum
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
mar 12 ago 2008 - 11:32
Salve a tutti, ho la necessità di inserire il percorso del mio database in un file txt e contestualmente
far leggere al mio programma in visual studio 2005 professional la stringa di connessione dal file txt
come faccio?
vi posto il mio codice di connessione inserito in un form
' Declare objects...
Dim objConnection As New SqlConnection _
("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Programmi\TEOR\Database.mdf;Integrated Security=True")
Dim objDataAdapter As New SqlDataAdapter( _
"SELECT CodiceFiscale, Grado, Cognome, " & _
"Nome, LuogoNascita, DataNascita, Indirizzo, Residenza, " & _
"EnteAppartenenza, CodEnte FROM dbo.Anagrafica", objConnection)
Dim objDataSet As DataSet
Dim objDataView As DataView
Dim objCurrencyManager As CurrencyManager
AL POSTO DELLA SEGUENTE STRINGA ("Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Programmi\TEOR\Database.mdf;Integrated Security=True")
VORREI FARGLI LEGGERE QUELLA INSERITA NEL FILE txt SALVATO NELLA DIRECTORY DOVE E ISTALLATO IL PROGRAMMA.
Grazie in anticipo
Mau67
Cteniza
Profilo
| Guru
1.509
messaggi | Data Invio:
mar 12 ago 2008 - 13:38
Questo lo puoi fare anche senza leggere le impostazioni da file di testo, cambia la configurazione e togli la path del database
Non considerando inoltre che esiste un file nella cartella bin .config apposta per questo scopo
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
mar 12 ago 2008 - 14:15
Cioè scusa non riesco a capire non ho molta esperienza, e non ho il file app.config nella mia applicazione
stò cercando di scrivere tutto via codice
Grazie
Mau67
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
mar 12 ago 2008 - 17:44
Così può andar bene?
Imports System
Imports System.IO
Imports System.Data.SqlClient
Public Class Form1
Private Const FILE_NAME As String = "C:\myConnectionString.txt"
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Not File.Exists(FILE_NAME) Then
MsgBox(FILE_NAME & " does not exist.")
Return
End If
Dim sr As StreamReader = File.OpenText(FILE_NAME)
Dim sqlString As String
sqlString = sr.ReadLine()
Me.Label1.Text = (sqlString) 'Questo è solo per verificare!
sr.Close()
Dim objConnection As New SqlConnection(sqlString)
Dim objDataAdapter As New SqlDataAdapter( _
"SELECT CodiceFiscale, Grado, Cognome, " & _
"Nome, LuogoNascita, DataNascita, Indirizzo, Residenza, " & _
"EnteAppartenenza, CodEnte FROM dbo.Anagrafica", objConnection)
Dim objDataSet As DataSet
Dim objDataView As DataView
Dim objCurrencyManager As CurrencyManager
End Sub
End Class
Ciao
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
mar 12 ago 2008 - 18:50
Il collegamento funziona egregiamente grazie.
Ho un altro problema, mi genera un errore in fase Update mi da il seguente errore (Sintassi non corretta in prossimità di 'CodiceFiscale'.)
Ti posto il codice AIUTAMI a trovare l'errore perfavore
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
If Not File.Exists(FILE_NAME) Then
MsgBox(FILE_NAME & " does not exist.")
Return
End If
Dim sr As StreamReader = File.OpenText(FILE_NAME)
Dim sqlString As String
sqlString = sr.ReadLine()
Me.ToolStripStatusLabel2.Text = (sqlString) 'Questo è solo per verificare!
sr.Close()
Dim objConnection As New SqlConnection(sqlString)
' Declare local variables and objects...
Dim intPosition As Integer
Dim objCommand As SqlCommand = New SqlCommand()
' Save the current record position...
intPosition = objCurrencyManager.Position
' Set the SqlCommand object properties...
objCommand.Connection = objConnection
objCommand.CommandText = "UPDATE Anagrafica" & _
"SET CodiceFiscale=@CodiceFiscale, Grado=@Grado, Cognome=@Cognome," & _
"Nome=@Nome, LuogoNascita=@LuogoNascita, DataNascita=@DataNascita," & _
"Indirizzo=@Indirizzo, Residenza=@Residenza, CodEnte=@CodEnte," & _
"EnteAppartenenza=@EnteAppartenenza, IndirizzoEnte=@IndirizzoEnte, CapEnte=@CapEnte," & _
"LuogoEnte=@LuogoEnte, IstitutoCredito=@IstitutoCredito, Agenzia=@Agenzia, & _
" IndirizzoIstituto=@IndirizzoIstituto," & _
"LuogoIstituto=@LuogoIstituto, Cap=@Cap," & _
"Prov=@Prov, PaeseCoord=@PaeseCoord, CinEstero=@CinEstero, Cin=@Cin," & _
"Abi=@Abi, Cab=@Cab, CC=@CC, ForzaArmata=@ForzaArmata," & _
"Categoria=@Categoria, LivParCod=@LivParCod, Sistema=@Sistema, Pagamento=@Pagamento," & _
"Missione=@Missione, CodMissione=@CodMissione,InizioMissione=@InizioMissione, & _
"FineMissione=@FineMissione WHERE IDUtente=@IDUtente"
objCommand.CommandType = CommandType.Text
' Add parameters for the placeholders in the SQL in the
' CommandText property...
' Parameter for the title column...
objCommand.Parameters.AddWithValue("@CodiceFiscale", txtCodiceFiscale.Text)
' Parameter for the type column
objCommand.Parameters.AddWithValue("@Grado", txtGrado.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@LivParCod", txtLivCodPar.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Cognome", txtCognome.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Nome", txtNome.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@LuogoNascita", txtLuogoNascita.Text)
' Parameter for the pubdate column
objCommand.Parameters.AddWithValue("@DataNascita", txtDataNascita.Text).DbType _
= DbType.DateTime
' Parameter for the title column...
objCommand.Parameters.AddWithValue("@Indirizzo", txtIndirizzo.Text)
' Parameter for the type column
objCommand.Parameters.AddWithValue("@Residenza", txtResidenza.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@EnteAppartenenza", txtEnteAppartenenza.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@CodEnte", txtCodEnte.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@IndirizzoEnte", txtIndirizzoEnte.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@CapEnte", txtCapEnte.Text)
' Parameter for the title column...
objCommand.Parameters.AddWithValue("@LuogoEnte", txtLuogoEnte.Text)
' Parameter for the type column
objCommand.Parameters.AddWithValue("@Sistema", cmbSistema.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Pagamento", cmbPagamento.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@PaeseCoord", txtPaese.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@CinEstero", txtCinEstero.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Cin", txtCin.Text)
' Parameter for the pubdate column
objCommand.Parameters.AddWithValue("@Abi", txtAbi.Text)
' Parameter for the title column...
objCommand.Parameters.AddWithValue("@Cab", txtCab.Text)
' Parameter for the type column
objCommand.Parameters.AddWithValue("@CC", txtCC.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@IstitutoCredito", txtIstituto.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Agenzia", txtAgenzia.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@IndirizzoIstituto", txtIndirizzoBanca.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@LuogoIstituto", txtLuogo.Text)
' Parameter for the title column...
objCommand.Parameters.AddWithValue("@Cap", txtCap.Text)
' Parameter for the type column
objCommand.Parameters.AddWithValue("@Prov", txtProvincia.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@InizioMissione", txtDataInizioMissione.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@CodMissione", txtCodMissione.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@FineMissione", cmbFineMissione.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@Missione", txtMissione.Text)
' Parameter for the price column...
objCommand.Parameters.AddWithValue("@ForzaArmata", cboForzaArmata.Text)
' Parameter for the title_id field...
objCommand.Parameters.AddWithValue _
("@IDUtente", BindingContext(objDataView).Current("IDUtente"))
' Open the connection...
objConnection.Open()
' Execute the SqlCommand object to update the data...
objCommand.ExecuteNonQuery()
' Close the connection...
objConnection.Close()
' Fill the DataSet and bind the fields...
FillDataSetAndView()
BindFields()
' Set the record position to the one that you saved...
objCurrencyManager.Position = intPosition
' Show the current record position...
ShowPosition()
' Display a message that the record was updated...
ToolStripStatusLabel1.Text = "Record Modificato"
End Sub
Mau67
Cteniza
Profilo
| Guru
1.509
messaggi | Data Invio:
mar 12 ago 2008 - 18:54
Quando scrivi i comandi, metti qualche spazio tra operandi operatori e istruzioni sql , giusto per la comprensione :)
Non credo che a sql server piaccia trovare UPDATE mytableSET piuttosto che UPDATE mytable SET
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
mar 12 ago 2008 - 19:23
Anche a me a prima vista sembra quello il problema!
Errato:
objCommand.CommandText = "UPDATE Anagrafica" & _
"SET CodiceFiscale=@CodiceFiscale, Grado=@Grado, Cognome=@Cognome," & _
Corretto:
objCommand.CommandText = "UPDATE Anagrafica" & _
" SET CodiceFiscale=@CodiceFiscale, Grado=@Grado, Cognome=@Cognome," & _
Ciao
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
mer 13 ago 2008 - 10:14
Grazie del prezziosissimo aiuto funziona benissimo siete mitici.
Vorrei chiuedere una altra cosa, se io il file myConnectionString.txt volessi copiarlo dentro la cartella del progetto e quindi quando lo distribuisco il cliente può istallare il programma in una directory diversa da quella definita da me e
quindi vorrei che il file venisse letto nella directry e non da C:\ come faccio
Private Const FILE_NAME As String = "C:\myConnectionString.txt"
Private Const FILE_NAME As String = "(QUI AL POSTO DI C:\ VORREI CHE LEGGESSE LA DIRECTORY )\myConnectionString.txt"
Grazie
Mau67
Cteniza
Profilo
| Guru
1.509
messaggi | Data Invio:
mer 13 ago 2008 - 10:19
Perchè reinventare ciò che già è disponibile?
Non hai che da usare il setting nel tuo progetto, vai nel progetto visualizza tutti i file, seleziona il file di setting, inserisci i tuoi valori.
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
mer 13 ago 2008 - 10:52
Ciao
Concordo con Cteniza nell'usare My.Settings
Con pochi passaggi ti togli il problema.
Se invece preferisci usare il file txt allora devi fare alcune prove utilizzando
Application.StartupPath
Private Const FILE_NAME As String = Application.StartupPath & "\myConnectionString.txt"
Ciao
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
mer 13 ago 2008 - 13:56
Ringrazio sempre per la disponibilità, la preparazione e la tempestività nelle risposte.
Devo porre un altro problema, cioè non riesco a filtrare i dati che carico in una listbox posta in un form e chiamata da un altro form vi posto il codice:
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Collections.Generic
Imports System.Text
Imports System.IO
Public Class SelezionaGrado
Private m_ParametroGrado As String
Public WriteOnly Property ParametroGrado() As String
Set(ByVal value As String)
m_ParametroGrado = value
End Set
End Property
' Declare objects...
Private Const FILE_NAME As String = "C:\myConnectionString.txt"
Dim objDataReader As System.Data.SqlClient.SqlDataReader
Dim cmd As New System.Data.SqlClient.SqlCommand
Private Sub SelezionaGrado_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
If Not File.Exists(FILE_NAME) Then
MsgBox(FILE_NAME & " does not exist.")
Return
End If
Dim sr As StreamReader = File.OpenText(FILE_NAME)
Dim sqlString As String
sqlString = sr.ReadLine()
Me.ToolStripStatusLabel2.Text = (sqlString) 'Questo è solo per verificare!
sr.Close()
Dim objConnection As New SqlConnection(sqlString)
Try
objConnection.Open()
cmd.CommandText = "SELECT IDGrado, Grado, ForzaArmata," & _
"Categoria, LivParCod, GradoEcon," & _
"Importo, Irpef FROM Gradi Where Categoria = " & m_ParametroGrado (QUI DOVREBBE FILTRARE)
cmd.Connection = objConnection
objDataReader = cmd.ExecuteReader
While objDataReader.Read
' Add new bindings to the DataView object...
ListBox1.Items.Add(objDataReader.Item("LivParCod") & Chr(9) & " " & objDataReader.Item("Grado") & Chr(9) & " " & objDataReader.Item("GradoEcon"))
End While
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
End Class
Dove sbaglio?
Come faccio a dare un intervallo tra una stringa e un altra incolonnando ? questa e la stringa
ListBox1.Items.Add(objDataReader.Item("LivParCod") & Chr(9) & " " & objDataReader.Item("Grado") & Chr(9) & " " & objDataReader.Item("GradoEcon"))
Mau67
Cteniza
Profilo
| Guru
1.509
messaggi | Data Invio:
mer 13 ago 2008 - 16:38
Nuova domanda, nuovo thread
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
mer 13 ago 2008 - 16:38
Prova a mettere il valore ParametroGrado tra gli apostrofi ('):
cmd.CommandText = "SELECT IDGrado, Grado, ForzaArmata," & _
"Categoria, LivParCod, GradoEcon," & _
"Importo, Irpef FROM Gradi Where Categoria = '" & m_ParametroGrado & "'"
Categoria = (apostrofo)(virgolette) & m_ParametroGrado & (virgolette)(apostrofo)(virgolette)
Ciao
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
mer 13 ago 2008 - 16:40
x Cteniza
questo è tempismo!!!
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
gio 14 ago 2008 - 08:55
alexmed sei mitico mi ai dato una grande mano funziona perfettamente, però non mi ai risposto come fare per distanziare perfettamente una stringa da un altra in un listbox e incolonnare?
esempio:
111111 aaaaaaaaaaaaaaaaaaa asasaas
141 jjkkjkjkjkkj yy
1333 aaaaaaaaaaaaaa ffdggfgfggfgffgfgfg
eccetera.
grazie
Mau67
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
gio 14 ago 2008 - 10:27
Ciao
Non ti ho risposto perchè credo che non ci sia un metodo per mettere in colonna i dati in una listbox
Tu vorresti un risultato del genere?
esempio:
111111 aaaaaaaaaaaaaaaaaaa asasaas
141 jjkkjkjkjkkj yy
1333 aaaaaaaaaaaaaa ffdggfgfggfgffgfgfg
Potresti provare a fare una cosa del genere se sai che le tue stringhe non saranno mai più lunghe di un certo valore
Supponiamo che le tue stringhe non siano mai più lunghe di 20 caratteri
Per ogni stringa calcoli la lunghezza ed aggiungi in spazi la differenza per arrivare a 20
Poi aggiungi un "vbTab" e dovresti riuscire a dargli un'incolonnamento
Se invece non hai idea, o cmq le tue stringhe sono di lunghezza molto variabile, potresti anteporre al caricamento un ciclo che ti calcola la stringa più lunga.
Da qui riparti con l'aggiunto di del "vbTab".
Sicuramente una procedura del genere ti rallenta molto il caricamento.
L'aternativa potrebbe essere caricare i tui dati in una Datagrid(View).
Ciao
Mau67
Profilo
| Expert
917
messaggi | Data Invio:
gio 14 ago 2008 - 10:50
grazie immensamente dell'aiuto e ti volevo chiedere se quando ho bisogno posso contattarti direttamente?
Sai stò sviluppando il mio progetto e o la necessita di terminarlo nel giro di qualche settimana,
e volevo chiederti qualche consiglio di come fare alcune opearazioni.
Ciao e grazie
Mau67
alexmed
Profilo
| Guru
1.186
messaggi | Data Invio:
gio 14 ago 2008 - 11:28
Prego!
Sicuramente puoi contattarmi, e sarò lieto di aiutarti per quanto mi è possibile.
Tieni presente cmq che qui nel forum ci sono utenti molto più esperti di me che possono e "vogliono" aiutarti.
Ciao
Torna su
Stanze Forum
Elenco Threads
Partecipa anche tu! Registrati!
Hai bisogno di aiuto ?
Perchè non ti registri subito?
Dopo esserti registrato potrai chiedere
aiuto sul nostro
Forum
oppure aiutare gli altri
Consulta le
Stanze
disponibili.
Registrati ora !