I seriously can't see any problem here. But I get the error
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" & Server.MapPath("App_Data/Database5.mdb"))
conn.Open()
Dim sql As String = "INSERT INTO Users VALUES (#firstName, #lastName)"
Dim txtFname As New TextBox
Dim txtLname As New TextBox
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#firstName", txtFname.Text)
cmd.Parameters.AddWithValue("#lastName", txtLname.Text)
cmd.Connection = conn
cmd.ExecuteNonQuery()
cmd.Dispose()
conn.Close()
Database: Id; autonumber
firstName; text
lastName; text
In addition to the comment I made, it's best to employ Using blocks for disposable resources such as connections and commands. Also note the absence of the two TextBoxes you were creating.
Using conn = New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=" & Server.MapPath("App_Data/Database5.mdb"))
conn.Open()
Using cmd = New OleDbCommand("INSERT INTO Users (FirstName, LastName) VALUES (#firstName, #lastName)", conn)
cmd.Parameters.AddWithValue("#firstName", txtFname.Text)
cmd.Parameters.AddWithValue("#lastName", txtLname.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Please correct your SQL:
INSERT INTO Users (firstName,lastName) VALUES (#firstName, #lastName)
Related
I'm using datetimepicker to choose the date to show the data from the microsoft sql server but the cells are empty.
I use LIKE operator to show the purchased item within the day.
This is the code:
Public Sub see4()
'MYPOPUL4TE D4T4GRIDVIEW3
Dim query As String = "SELECT * FROM projectsd.dbo.cart WHERE dates LIKE '" & DateTimePicker1.Text & "'"
Using cmd As SqlCommand = New SqlCommand(query, con)
Using da As New SqlDataAdapter
da.SelectCommand = cmd
Using dt As New DataTable()
da.Fill(dt)
DataGridView3.DataSource = dt
End Using
End Using
End Using
End Sub
Attempting to fill a data table using SqlDataAdapter with a WHERE clause but it returns nothing. The SQL command itself returns data from SSMS and removing just the WHERE clause in code fills data table as expected.
Dim adapter As New SqlDataAdapter
Dim datatable As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
adapter = New SqlDataAdapter("SELECT * FROM [MyProjectDtbl] WHERE zipcode = 22021", cnn)
adapter.Fill(datatable)
adapter.Dispose()
End Using
Digging through the Select command EventSink, I found:
Unable to cast object of type 'System.Data.SqlClient.SqlInternalConnectionTds' to type 'System.Data.SqlClient.SqlInternalConnectionSmi'
Try it with parameters.
Private Sub OPCode()
Dim dt As New DataTable
Using cnn As New SqlConnection(connectionString),
cmd As New SqlCommand("SELECT * FROM [MyProjectDtbl] WHERE zipcode = #zip", cnn)
cmd.Parameters.Add("#zip", SqlDbType.Int).Value = 22021
cnn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Debug.Print(dt.Rows.Count.ToString)
End Sub
I am trying to allow the user to select which table they want to take their data from, the UserID text box(UserIDtb) is where the user inputs the table they want. I've tried several different ways of doing it but cant seem to allow the user to select a specific table. This is the code I have so far:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfirmIDButt.Click
Chart1.Series.Add("Score")
Dim Conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile = "\users.accdb" ' Change it to your Access Database location
Conn.ConnectionString = provider & dataFile
Conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Month], [Score] FROM [Table]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Score").Points.AddXY(dr("Month").ToString, dr("Score").ToString)
End While
dr.Close()
cmd.Dispose()
End Sub
I am trying to insert data into my Access database using vb for an application I am building. I have been BEATING my had off of an invisible wall trying to get the data to enter into the database. Below is the code, below that I will explain it more.
Private Sub btnSubmitExpense_Click(sender As Object, e As EventArgs) Handles btnSubmitExpense.Click
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\PFADatabase.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "Insert into Expenses ([ExpenseTypeID], [DateOfExpense],[AmountOfExpense]) Values(?,?,?)"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
cmd.Parameters.Add(New OleDbParameter("ExpenseTypeID", CType(cboCategoryOfExpense.Text, String)))
cmd.Parameters.Add(New OleDbParameter("DateOfExpense", CType(dateOfExpense.Text, String)))
cmd.Parameters.Add(New OleDbParameter("AmountOfExpense", CType(txtAmountOfExpense.Text, String)))
Try
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
'clear the form below
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
[ExpenseTypeID] is actually a lookup. The object is a combobox in vb that I have programmed above the code I posted here.
[DateOfExpense] is also a Date object in VB. I just dragged it over. I want that to be associated with everything in that table.
[AmountOfExpense] is again, tied into the db.
Basically a user enters the date using the tool, then chooses a category of their expense and then enters the amount. This is all one table but the expenseType is a Lookup actually within Access to another table so we could have the dropdown. Everything works well until I click the save button. Then whenever i do that I get the exception the type is mismatched. How do I fix that? I'm GUESSING it is the text string being wrong, but I've tried other things so I am thinking it is a bit more than that which is why I came here to you professionals to get input.
Thank you.
EDIT: The error is coming in at
cmd.ExecuteNonQuery()
and says "Data type mismatch in criteria expression. "
'START THE POPULATE THE COMBO BOXES
'Gets the database and makes the connection
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "C:\PFADatabase.accdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
'Generates a query command
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [ExpenseType] FROM [ExpenseType]", myConnection)
myConnection.Open() 'Opens connection
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
cboCategoryOfExpense.Items.Add(dr.Item(0))
End While
myConnection.Close()
'END THE POPULATE OF COMBO BOXES
As you can see in the comments, it is saying how the combo boxes are populated.
EDIT: In the picture under Expenses is the main table. The circled value is the FK and it's leading to the PK of the ExpenseType. The data we are pulling the drop down from is the ExpenseType under ExpenseType. From what I understand, you guys are saying, and I agree, it's writing to the PK of ExpenseType and not the data. ALL I want it to do is keep the data categorized for a graph we will be using.
Convert your input to the appropriate datatype as required by your columns. If you don't specify the datatype of your parameters and pass always strings then you are easy target of this kind of errors
...
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Dim expID As Integer
if Not Int32.TryParse(cboCategoryOfExpense.Text, expID) Then
MessageBox.Show("Invalid integer")
return
End If
cmd.Parameters.Add("ExpenseTypeID", OleDbType.Integer).Value = expID
Dim dtExp as DateTime
if Not DateTime.TryParse(dateOfExpense.Text, dtExp) Then
MessageBox.Show("Invalid Date")
return
End If
cmd.Parameters.Add("DateOfExpense", OleDbType.Date).Value = dtExp
Dim amount As Decimal
if Not Decimal.TryParse(txtAmountOfExpense.Text, amount) Then
MessageBox.Show("Invalid Decimal")
return
End If
cmd.Parameters.Add("AmountOfExpense", OleDbType.Currency).Value = amount
....
Looking at your edit and comments, perhaps this is what you need
' Be sure to have a combobox with DropDownList style to avoid
' user entering an unexpected value then....
'Load the combobox from the table ExpenseType
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [ExpenseTypeID], " & _
"[ExpenseType] FROM [ExpenseType]", myConnection)
myConnection.Open() 'Opens connection
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim dt = new DataTable()
dt.Load(dr)
cboCategoryOfExpense.DataSource = dt
' The visible part of the combo contains value from ExpenseType field
cboCategoryOfExpense.DisplayMember = "ExpenseType"
' The hidden part refers to the ExpenseTypeID field
cboCategoryOfExpense.ValueMember = "ExpenseTypeID"
...
and now when converting the combobox value you coud write
Dim expID As Integer
' Sanity check in case the user want to insert but has not
' selected anything from the combobox
if cboCategoryOfExpense.SelectedValue Is Nothing Then
MessageBox.Show("Select an Expense")
return
End if
cmd.Parameters.Add("ExpenseTypeID", OleDbType.Integer).Value = Convert.ToInt32(cboCategoryOfExpense.SelectedValue)
....
I'm trying to retrieve data from sql server to vb.net textbox but i don't know what else to do all the tutorials i have are just to retrieve records from the database to datagrid view..please help..
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
cn.Open()
With cmd
.Connection = cn
.CommandText = "SELECT * FROM Students WHERE RFID like '%" & txtrfid.Text & "%'"
End With
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
da.SelectCommand = cmd
dt.Clear()
da.Fill(dt)
cn.Close()
txtname.Text = 'Firstname'
You're populating a DataTable with the data from the database so you then have to get the data from that DataTable into the TextBox. You can do that with data binding, which is how you've probably seen it done with a grid, e.g.
txtname.DataBindings.Add("Text", dt, "Firstname")
That's definitely how you'd do it if you were retrieving multiple records that you wanted to be able to navigate, although you'd probably use a BindingSource in between. If there's only one record then you might instead just move the data manually, e.g.
txtname.Text = CStr(dt.Rows(0)("Firstname"))
If you want to display only a single value (FirstName) from Table then see following piece of code
Using conn As New SqlConnection("connstr")
conn.Open()
Dim cmd As New SqlCommand("", conn)
Dim txtName As String
cmd.CommandText = "SELECT firstname FROM Students WHERE RFID ='" & txtrfid.Text & "'"
txtName = IIf(IsDBNull(cmd.ExecuteScalar), "", cmd.ExecuteScalar)
If txtName <> "" Then
MsgBox("Record Found!", MsgBoxStyle.Information, "Update")
Textbox1.Text = ""
Textbox1.Text = txtName
else
MsgBox("No Record Found!", MsgBoxStyle.Information, "INFO.")
End If
End Using
There are many ways to retrieve the data. You can simply retrieve the data from sql database to textbox using sql data reader which is one of my favourite. Let me share to you.
Note : Don't forget to import system.data.sqlclient
Private Sub txtrfid_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles txtrfid.KeyPress
strConn = "Data Source=" & servernamehere & ";Initial Catalog=" & databasenamehere & ";User ID=" & userid & ";Password=" & password
sqlConn = New SqlConnection(strConn)
sqlConn.Open()
Dim sqlcmd As New SqlCommand("Your query here", sqlConn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
txtrfid.Text = myreader.Item("column name from sql database table").Tostring
End If
sqlConn.Close()
End Sub
You may catch the exception with Try-Catch Technique.