I'm new to programming. What i'm trying to accomplish is to fill in 9 textboxes in VB.NET, reading access table TblKlanten, using a combobox (CbbNaamfirma). I cannot get this to work for the life of me; i've been searching for 6 hours for this simple thing. Can any of you help me out? I've read numerous threads on SO.com like this and they all just won't work for me.
Code i have now:
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim Connection As New OleDb.OleDbConnection
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" & Application.StartupPath & "\Database.accdb.'"
Try
Connection.Open()
Dim query As String
query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ' " & CbbNaamfirma.Text & " ' "
Dim cmd As New OleDbCommand(query, Connection)
Dim Reader As OleDbDataReader = cmd.ExecuteReader
Reader = cmd.ExecuteReader
While Reader.Read
TxtAdresprev.Text = Reader.GetString("Adres")
End While
Connection.Close()
Catch ex As OleDbException
MessageBox.Show(ex.Message)
Finally
Connection.Dispose()
End Try
End Sub
Thank you in advance. Hope that code block turned out alright?
The first thing to change is the reading from the database using a parameterized query. Notice that your code cannot find anything because you add a space before and after the value of the combobox.
Then you need to start employing the using statement around the disposable objects to ensure a proper closing and disposing
Finally the GetString method from the OleDbDataReader wants a numeric index inside the returned list of fields, not the name of the field
Private Sub CbbNaamfirma_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles CbbNaamfirma.SelectedIndexChanged
Dim cnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & _
Application.StartupPath & "\Database.accdb"
Dim query = "SELECT Adres FROM TblKlanten WHERE [Naam firma] = ?"
Using Connection = New OleDb.OleDbConnection(cnString)
Using cmd = New OleDbCommand(query, Connection)
Try
Connection.Open()
cmd.Parameters.AddWithValue("#p1", CbbNaamfirma.Text)
Using Reader = cmd.ExecuteReader
While Reader.Read
Dim posAdres = Reader.GetOrdinal("Adres")
TxtAdresprev.Text = Reader.GetString(posAdres)
.... other text boxes for other fields here.....
End While
End Using
Catch ex As OleDbException
MessageBox.Show(ex.Message)
End Try
End Using
End Using
End Sub
Also your connection string seems to be wrong. No need of quotation and that stray point after the fielname is wrong
Related
i put this code because i used combobox and they fill my two textbox,but when try to save its not saving the data that i put
this is the code
Sub loaddata()
Try
reload("SELECT * FROM NAME", STUDENT)
STUDENT.DataSource = dt
STUDENT.DisplayMember = "NAME"
STUDENT.ValueMember = "ID"
Catch ex As Exception
End Try
End Sub
Private Sub NAME_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NAME.SelectedIndexChanged
Try
Dim sql As String
Dim cmd As New OleDbCommand
Dim dt As New DataTable
Dim da As New OleDbDataAdapter
strcon.Open()
sql = "SELECT * FROM STUDENT where NAME LIKE '%" & NAME.Text & "%'"
cmd.Connection = strcon
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
If dt.Rows.Count > 0 Then
GENDER.Text = dt.Rows(0).Item("GENDER").ToString
ADDRESS.Text = dt.Rows(0).Item(" ADDRESS").ToString
End If
Catch ex As Exception
Finally
strcon.Close()
End Try
End Sub
please show me how to put the save codes here,because i use only the BindingNavigator1 to save, but it does not save, sorry if my grammar is wrong because i'm not a fluent in english
I know we have a language barrier but we are both trying our best. I have provided a few examples of code to interact with a database.
It is a good idea to keep you database code separate from you user interface code. If you want to show a message box in you Try code, keep the Try in the user interface code. The error will bubble up from the database code to the calling code.
Using...End Using blocks take care of disposing of database objects. Parameters protect against Sql injection because parameter values are not considered executable code by the database. Note that for OleDb data sources the order that the parameters appear in the sql statement must match the order that they are added to the Parameters collection.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Dim dt = GetOriginalData()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"
ComboBox1.DataSource = dt
End Sub
Private Function GetOriginalData() As DataTable
Dim dt As New DataTable
Using cn As New OleDbConnection("Your first connection string"),
cmd As New OleDbCommand("Select ID, Name From Table1;")
cn.Open()
Using reader = cmd.ExecuteReader
dt.Load(reader)
End Using
End Using
Return dt
End Function
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
InsertData(CInt(ComboBox1.SelectedValue), ComboBox1.SelectedText, txtGender.Text, txtAddress.Text)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub InsertData(id As Integer, name As String, gender As String, address As String)
Using cn As New OleDbConnection("Your second connection string"),
cmd As New OleDbCommand("Insert Into Table2 (ID, Name, Gender, Address) Values (#ID, #Name, #Gender, #Address);", cn)
With cmd.Parameters
.Add("#ID", OleDbType.Integer).Value = id
.Add("#Name", OleDbType.VarChar).Value = name
.Add("#Gender", OleDbType.VarChar).Value = gender
.Add("#Address", OleDbType.VarChar).Value = address
End With
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
I have the following code for a login winform. When I make the connection to the database and make a select statement I get no rows back. I'm getting the message "No data exists for the row/column."
But there are rows and columns in the database.
Can someone tell me what I do wrong?
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Using con As New OleDbConnection(connectionString)
Dim intResult As Integer = 0
' MsgBox(connectionString)
Try
con.Open()
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikers.Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
Using dr As OleDbDataReader = cmd.ExecuteReader()
'intResult = CInt(cmd.ExecuteScalar)
'If intResult > 0 Then
MsgBox(dr.Item("Gebruikersnaam").ToString)
'End If
With dr
While .Read()
MsgBox(.HasRows)
'MsgBox(.Item("Gebruikersnaam"))
'TextBox1.Text = .Item("Gebruikersnaam") & vbCrLf
End While
End With
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
con.Close()
End Try
Me.Close()
End Using
End Sub
The problem was checking dr.Item() before ever calling dr.Read(). Aside from the that, make sure the username in UsernameTextBox actually exists in the database, fix those nasty plain-text passwords, and you'll be fine.
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim connectionString As String = System.Configuration.ConfigurationManager.ConnectionStrings("MySqlConnectionString").ConnectionString
Try
Dim result As New StringBuilder()
Using con As New OleDbConnection(connectionString)
Using cmd As New OleDbCommand("SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = #Username", con)
cmd.Parameters.AddWithValue("#Username", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#Password", PasswordTextBox.Text)
con.Open()
Using dr As OleDbDataReader = cmd.ExecuteReader()
While dr.Read()
'MsgBox(dr("Gebruikersnaam"))
result.AppendLine(dr("Gebruikersnaam"))
End While
End Using
End Using
End Using
TextBox1.Text = result.ToString()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
One final concern. I'm not sure which OLE provider you're using, but last time I checked most providers where it makes sense to use OLE want you to use ? placeholders instead of named parameters. So the SQL command would look like this:
SELECT Gebruikersnaam FROM Gebruikers WHERE Gebruikersnaam = ?
But if you're really using MySql, as the connection string name suggests, you really do so much better getting the real MySql ADO.Net library instead of OleDB: minor performance gain, better error messaging, etc.
The code executes everything but the While dataReader.Read() loop and I have no idea why. No errors are coming up, it just doesn't actually read the data with the data reader. Many thanks for any help received.
Private Sub BtnFind_Click(sender As Object, e As EventArgs) Handles BtnFind.Click
Dim cmd As OleDbCommand
Dim myConnection As OleDbConnection
Dim text As String = txtTeacherID.Text
Dim dataReader As OleDbDataReader
Try
'selects the information from the row where the column has the teacher ID
myConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\My Documents\database.accdb")
myConnection.Open()
cmd = New OleDbCommand("SELECT * FROM [TMessages] WHERE TeacherID = '" & text & "'", myConnection)
dataReader = cmd.ExecuteReader
While dataReader.Read()
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
lstItems.Items.Add(dataReader(0))
MsgBox("reading")
End While
Catch
MsgBox("Error occured")
End Try
dataReader.Close()
myConnection.Close()
End Sub
As pointed in my comment, you are only reading the same value 3 times
lstItems.Items.Add(dataReader(0))
And the read value may be in blank, try to use your reader to read all the values recieved in the dataReader thought a loop and check all the values.
for i = 0 to dataReader.FieldCount
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim a As New OpenFileDialog
con.ConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\USERS\USER\DOWNLOADS\SDP(BACKUP1)\SDP(BACKUP)\SDP.MDF;Integrated Security=True"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Announcement ([name],[picture]) VALUES('" & nameTB.Text & "',#a2)"
cmd.Parameters.Add(New SqlClient.SqlParameter("#a2", SqlDbType.Image)).Value = IO.File.ReadAllBytes(PictureBox2.BackgroundImage)
cmd.ExecuteNonQuery()
MsgBox("Event Announcement submitted!")
con.Close()
Catch ex As Exception
MsgBox("Operation Failed! Please Check Again!")
End Try
End Sub
this is what i had try....i can choose a image but i cant save it(which mean complete save a picture into database) all that thing in google teach me save picture in sql server or access.. i had try it...but the very last thing i dunt understand is how can i parameter #a2 with picturebox?
it give error for IO.File.ReadAllBytes(PictureBox2.BackgroundImage)
As commented, File.ReadAllBytes wants a file, not an image. So you need to use a MemoryStream instead:
Using ms As New MemoryStream
PictureBox2.BackgroundImage.Save(ms, ImageFormat.Png)
cmd.Parameters.AddWithValue("#a2", ms.ToArray)
End Using
' OK button
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim con As New OleDbConnection("Provider=Microsoft.jet.oledb.4.0;data source=C:\Users\Jill\Desktop\saddbase\Sadsystem\Sadsystem\bin\Debug\tenant.mdb")
Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM info WHERE TN_ID = '" & UsernameTextBox.Text & "' AND Password = '" & PasswordTextBox.Text & "' ", con)
con.Open()
Dim sdr As OleDbDataReader = cmd.ExecuteReader()
' If the record can be queried, Pass verification and open another form.
If (sdr.Read() = True) Then
MessageBox.Show("The user is valid!")
Me.Hide()
Else
MessageBox.Show("Invalid Tenant ID or password!")
End If
When I run the program there's an error in cmd.ExecuteReader(). Data type mismatch in criteria expression please help how to fix this error.
In your query you pass two strings for the TN_ID and Password fields.
Probably the TN_ID is a numeric field and you don't need to put quotation marks around it and I find really strange that you pass the value of a UserName textbox.
Said that, I wish to examine your query because there are potential problems that you have not seen:
First of all PASSWORD is a reserved Keyword and thus you need to use Square Brackets around it.
Second, do not use string concatenation to build sql commands but use a parameterized query like this
Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK.Click
Dim commandText = "SELECT * FROM info WHERE TN_ID = ? AND [Password] = ?"
Using con = New OleDbConnection(......))
Using cmd = New OleDbCommand(commandText,con))
con.Open()
' If the TN_ID is really a numeric field then you need '
' to conver the first parameter to a number '
' cmd.Parameters.AddWithValue("#p1", Convert.ToInt32(UsernameTextBox.Text))'
cmd.Parameters.AddWithValue("#p1", UsernameTextBox.Text)
cmd.Parameters.AddWithValue("#p2", PasswordTextBox.Text)
Using sdr As OleDbDataReader = cmd.ExecuteReader())
.....
End Using
End Using
End Using
End Sub
As a side note, not related to your problem, consider also to NOT store password in plain text in the database. There are techniques that HASH the password text and store the result in the database. In this way none can get the password simply looking at the database file. See the details in this question
Private Sub SumOfIR()
Try
Dim con As New System.Data.OleDb.OleDbConnection(ConnectionString)
Dim com As New System.Data.OleDb.OleDbCommand
con.Open()
com.Connection = con
com.CommandText = "Select Sum(IR) from Spectrum where StdNu='" + TxtNuTeif.Text + "'"
com.Parameters.Clear()
Dim SumIR As OleDbDataReader = com.ExecuteScalar
LblIRTeif.Text = com.ExecuteScalar("SumIR").ToString
con.Close()
com.Dispose()
Catch ex As Exception
BehComponents.MessageBoxFarsi.Show(ex.ToString, "", BehComponents.MessageBoxFarsiButtons.OK, MessageBoxIcon.Warning)
End Try
End Sub