Retrieving/adding data from/to a stored procedure - sql

Alright so I have this webpage that I have to create and it has 3 pages and a master page. Now basically all of it is working, except the fact that I can't seem to get data coming into the webpage when requested via a retrieve button, nor will it update or add data to the SQL table. Now in my queries page when I put Select * From Customer it brings back the data in the table so that part works. From what I have to work with in the pdf's provided, they want me to use
TextBox1.Text = table.Rows(0).Field<string>("TextBox1")
TextBox1.DataBind()
To retrieve the data from the sql, now it comes up with an error saying Overload resolution failed because no accessible 'Field' accepts this number of arguments.
So here is my Customer page
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Data.DataRowCollection
Public Class Customer
Inherits System.Web.UI.Page
Dim conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Shadows adapter As SqlDataAdapter = New SqlDataAdapter()
// Tells me to use Shadows because variable adapter conflicts with property 'adapter'
Dim table As DataTable = New DataTable()
Dim command As SqlCommand = New SqlCommand()
Protected Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
Try
conn = New SqlConnection(ConfigurationManager.ConnectionStrings("dbConnection1").ConnectionString)
Dim command As SqlCommand = New SqlCommand()
command.Connection = conn
command.CommandType = CommandType.Text
command.CommandText = "INSERT INTO Acme_Customer VALUES(" & txtCustID.Text & ",'" & txtFirstname.Text & "', '" & txtSurname.Text & "', " & txtGender.Text & ", " + txtAge.Text & ", " & txtAddress1.Text & ", " & txtAddress2.Text & ", " & txtCity.Text & ", " + txtPhone.Text & ", " + txtMobile.Text & ", " & txtEmail.Text & ")"
command.Connection.Open()
adapter.InsertCommand = command
adapter.InsertCommand.ExecuteNonQuery()
command.Connection.Close()
Clear()
lblMessage.Text = "You have been successfully added into our records"
Catch ex As Exception
lblMessage.Text = "Something has gone wrong with adding you to our records, please double check everything as we want you to become a member."
End Try
End Sub
Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
txtFirstname.Text = table.Rows(0).Field<string>("Firstname")
txtFirstname.DataBind()
txtSurname.Text = table.Rows(0).Field<string>("Surname")
txtSurname.DataBind()
txtGender.Text = table.Rows(0).Field<String>("Gender")
txtGender.DataBind()
txtAge.Text = table.Rows(0).Field<Integer>("Age")
txtAge.DataBind()
txtAddress1.Text = table.Rows(0).Field<String>("Address1")
txtAddress1.DataBind()
txtAddress2.Text = table.Rows(0).Field<String>("Address2")
txtAddress2.DataBind()
txtCity.Text = table.Rows(0).Field<String>("City")
txtCity.DataBind()
txtPhone.Text = table.Rows(0).Field<Integer>("Phone Number")
txtPhone.DataBind()
txtMobile.Text = table.Rows(0).Field<Integer>("Mobile Number")
txtMobile.DataBind()
txtEmail.Text = table.Rows(0).Field<String>("Email")
txtEmail.DataBind()
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub
So I'm just wondering what I've written wrong or if I should be using other code instead of what I have here, I know I should be using C# but I just got the hang of vb so, hopefully I can just start using C# after this project.

Protected Sub btnRetrieve_Click(sender As Object, e As EventArgs) Handles btnRetrieve.Click
Try
command.Connection = conn
command.CommandType = CommandType.StoredProcedure
command.CommandText = "GetCustomer"
command.Connection.Open()
Dim param As SqlParameter = New SqlParameter()
param.ParameterName = "#ID"
param.SqlDbType = SqlDbType.Int
param.Direction = ParameterDirection.Input
param.Value = txtCustID.Text
command.Parameters.Add(param)
adapter.SelectCommand = command
adapter.Fill(table)
dim objDV as dataview = table.defaultview
txtFirstname.Text = objDV(0)("Firstname").tostring
txtSurname.Text = objDV(0)("Surname").tostring
' Fill all other text boxes following above lines
Catch ex As Exception
lblMessage.Text = "The ID you have entered doesn't exist."
End Try
End Sub

Related

Using 2 combo boxes to populate a datagridview in VB.NET

I having problems understanding why my one of my comboboxes displays a filtered search but the other one doesn't, I am using the same code for both comboboxes but modified some SQL queries linked to my database. I have also noticed that when I remove or comment out the code for any one of the comboboxes the the filtered search happens for the one hasn't been commented or removed. I also used an "If, Else" statement but still doesn't work. I would also want for both comboboxes to be used to filter a datagridview. Just to keep in mind once the item is selected from the combobox a search button is pressed to filer/display data into the datagridview.
Kind Regards
Here is my code and form:
[Redundant Data being displayed] https://i.stack.imgur.com/JEQI4.png
[ComboBox Brand works as intended] https://i.stack.imgur.com/6YyBf.png
[ComboBox Category displays everything rather than displaying the category chosen] https://i.stack.imgur.com/oEfII.png
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
If Not CmbBrand.SelectedIndex & CmbCategory.SelectedIndex = Nothing Then
BrandDisplay()
ElseIf CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
CategoryDisplay()
ElseIf Not CmbBrand.SelectedIndex & Not CmbCategory.SelectedIndex = Nothing Then
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
End If
cn.Close()
End Sub
Private Sub BrandDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STBrand Like #BrandSearch"
.Parameters.AddWithValue("#BrandSearch", "%" & CmbBrand.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Brand from the drop down list", "Brand", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
Private Sub CategoryDisplay()
If DbConnect() Then
DgvRecord.Rows.Clear()
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Select * " &
"From TblStock " &
"Where STCategory Like #CategorySearch"
.Parameters.AddWithValue("#CategorySearch", "%" & CmbCategory.Text & "%")
Dim rs As OleDbDataReader = .ExecuteReader()
SQLCmd.ExecuteReader()
While rs.Read
Dim NewStockRow As New DataGridViewRow()
NewStockRow.CreateCells(DgvRecord)
NewStockRow.SetValues({rs("StockID"), rs("STDateTime"), rs("STCategory"), rs("STBrand"), rs("STItemDescription"), rs("STSerialNumber"), rs("StockIn"), rs("StockOut"), rs("Stock")})
NewStockRow.Tag = rs("StockID")
DgvRecord.Rows.Add(NewStockRow)
End While
rs.Close()
If DgvRecord.Rows(0).Selected = True Then
MessageBox.Show("Please select a Category from the drop down list", "Category", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End If
End With
End If
cn.Close()
End Sub
```
It is a good idea to separate your User Interface code from you database code. Your event procedure code should be rather brief.
Declare your Connections, Commands and DataReaders in the method where they are used so they can be disposed. Using...End Using blocks do this for us; they also close the connection. Pass your connection string directly to the constructor of the connection.
We have a different CommandText and ParametersCollection for each possibility. For Sql Server use the Add method rather than AddWithValue.
Private Sub BtnSearch_Click(sender As Object, e As EventArgs) Handles BtnSearch.Click
Dim dt = GetSearchData(CmbBrand.Text, CmbCategory.Text)
DGVRecord.DataSource = dt
End Sub
Private Function GetSearchData(Brand As String, Category As String) As DataTable
Dim dt As New DataTable
Dim sqlString = "Select * From From TblStock "
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If Not String.IsNullOrEmpty(Brand) AndAlso Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch And STBrand = #BrandSearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Brand) Then
cmd.CommandText = sqlString & "Where STBrand = #BrandSearch;"
cmd.Parameters.Add("#BrandSearch", SqlDbType.VarChar).Value = Category
ElseIf Not String.IsNullOrEmpty(Category) Then
cmd.CommandText = sqlString & "Where STCategory = #CategorySearch;"
cmd.Parameters.Add("#CategorySearch", SqlDbType.VarChar).Value = Brand
Else
cmd.CommandText = sqlString & ";"
End If
cn.Open()
Using reader = cmd.ExecuteReader()
dt.Load(reader)
End Using
End Using
Return dt
End Function
For better understanding you need to change those first "if... then... else...".
If the combobox is not selected it will have value -1 so you can do it like this:
Dim bBrandIsSelected as boolean = CmbBrand.SelectedIndex <> -1
Dim bCategoryIsSelected as boolean = CmbCategory.SelectedIndex <> -1
Now you can build the code more easily like:
If bBrandIsSelected AndAlso bCategoryIsSelected then
' do something
else
if bBrandIsSelected then
BrandDisplay()
else
if bCategoryIsSelected then
CategoryDisplay()
End if
End if
End if

Use VB.NET Manipulate Microsoft Access Database

How can I make this work?
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
conndb = New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
COMMAND = New OleDbCommand(str, conndb)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
conndb.Dispose()
End Try
End Sub
I need help on how can I make this run without errors, Im using ms access as my database source. There seems to be an error using this code, this code works perfectly fine with mysql but in ms access, it says data mistype error or something like that. Need your help, thanks
Remove the ' surrounding the field CustomerID in your query :
str = "Select * FROM customer WHERE CustomerID = '" & ListView.FocusedItem.Text & "'"
becomes :
str = "Select * FROM customer WHERE CustomerID = " & ListView.FocusedItem.Text
MS Access sees a string when you put an apostrophe, so there is a Type Mismatch Exception, because it is expecting a number...
However, this is a pretty bad idea as Parametrized queries are a better way of doing this (see : Why should I create Parametrized Queries ?)
Also, Use Using
So all in all, it's just another brick in the wall :
Private Sub ListView_MouseClick(sender As Object, e As MouseEventArgs) Handles ListView.MouseClick
Using conndb As New OleDbConnection
conndb.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\Database1.accdb"
Try
conndb.Open()
Dim str As String
str = "Select * FROM customer WHERE CustomerID = #Customer"
Using COMMAND As New OleDbCommand(str, conndb)
COMMAND.Parameters.Add("#Customer", SqlDbType.Integer).Value = Integer.Parse(ListView.FocusedItem.Text)
dr = COMMAND.ExecuteReader
If dr.Read = True Then
txtID.Text = dr("CustomerID")
txtFirstName.Text = dr("FirstName")
txtSurname.Text = dr("Surname")
txtAddress.Text = dr("Address")
txtCN1.Text = dr("ContactNo1")
txtCN2.Text = dr("ContactNo2")
txtEmail.Text = dr("EmailAddress")
txtRemarks.Text = dr("Remarks")
txtDebtStatus.Text = dr("DebtStatus")
txtDownPay.Text = dr("DownPayment")
txtDebtBal.Text = dr("DebtBal")
txtCustomerDate.Text = dr("Date")
End If
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
End Sub
Take a look at this sample code that I put together a while back. You can probably learn a lot from this.
Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\your_path\Desktop\Northwind_2012.mdb"
Dim selectCommand As String
Dim connection As New OleDbConnection(connectionString)
'selectCommand = "Select * From MyExcelTable where Fname = '" & TextBox1.Text & "'"
'"SELECT * FROM Customers WHERE Address LIKE '" & strAddressSearch & "%'"
'or ending with:
'"SELECT * FROM Customers WHERE Address LIKE '%" & strAddressSearch & "'"
selectCommand = "Select * From MyExcelTable where Fname Like '" & TextBox1.Text & "%'"
Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)
With DataGridView1
.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
End With
Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
Dim table As New DataTable()
table.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(table)
Me.bindingSource1.DataSource = table
Dim data As New DataSet()
data.Locale = System.Globalization.CultureInfo.InvariantCulture
DataGridView1.DataSource = Me.bindingSource1
Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
Me.DataGridView1.AutoResizeColumns( _
DataGridViewAutoSizeColumnsMode.AllCells)
End Sub

SQL Update not updating records in access

Trying to update the values of Comment and ProgressValue inside a table in access. The message box at the end pops up but none of the values are changed.
Sub UpdateWeeklyReport()
Dim con As OleDbConnection
Dim com As OleDbCommand
con = New OleDbConnection("provider=microsoft.jet.oledb.4.0;data source=C:\ProjectDatabase.mdb")
com = New OleDbCommand("Update WeeklyReport Set Comment = #Comment, ProgressValue = #ProgressValue Where [EntryDate]='" & CBDate.SelectedValue.ToString & "' AND [AdminNo]=" & CBAdmin.SelectedValue & " AND [ClassCode]='" & CBClass.SelectedItem.ToString & "'", con)
con.Open()
com.Parameters.Add("#Comment", OleDbType.LongVarChar).Value = txtComment.Text
com.Parameters.Add("#ProgressValue", OleDbType.Integer).Value = CBProgress.Text
com.ExecuteNonQuery()
con.Close()
MessageBox.Show("Report Changed")
intialconnection()
End Sub
End Class

vb.net msaccess update, may i ask whats wrong, why it does not update my data base?

I don't know what seems to be the problem,
can anyone help?
I already installed all necessary thing to run the program.
Public Sub main1_Click(sender As Object, e As EventArgs) Handles main1.Click
scorestanding.Text = standingscore
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
dataFile = "Database\user.mdb"
connString = provider & dataFile
myConnection.ConnectionString = connString
myConnection.Open()
Dim str As String
str = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.CommandText = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.Close()
main.Show()
End Sub
str = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
Try
cmd.CommandText = "UPDATE login set[scorestand] = '" & scorestanding.Text & "' Where [username] = '" & Label1.Text
cmd.ExecuteNonQuery()
cmd.Dispose()
myConnection.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.Close()
main.Show()
End Sub
It does nt have any eror but it also does nothing.

Why is Data Not Saved to the Database in my Guestbook Application?

I am creating an application that requires a guestbook.. The data from the database appears on the website however any data I enter from the website doesn't automatically get put into the database.
Here is the code I have..
Protected Sub ButSign_Click(sender As Object, e As EventArgs) Handles ButSign.Click
Dim strDSN As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "
Data source=C:\USERS\SHAUNA WATSON\DESKTOP\PROJECT COPIES\FINAL\APP_DATA\FACTORY.MDF"
Dim strSQL As String = (((("INSERT INTO Guestbook " & "( Name,Address,Email,Comments)" & "VALUES ('")
+ TxtName.Text.ToString() & " ',' ") + TxtAddress.Text.ToString() & " ', '") + TxtEmail.Text.ToString() & " ',' ") + TxtComments.Text.ToString() & " ')"
' set Access connection and select strings
' Create oleDbDataAdapter
Dim myConn As New OleDbConnection(strDSN)
'Create ole Db Command And call ExecuteNonQuery to execute
' a SQL statement
Dim myCmd As New OleDbCommand(strSQL, myConn)
Try
myConn.Open()
myCmd.ExecuteNonQuery()
Catch exp As Exception
Console.WriteLine("Error: {0}", exp.Message)
End Try
myConn.Close()
' open Thans.aspx page after adding entries to the guest book
Response.Redirect("GuestbookThanks.aspx")
End Sub
I'm just wondering if anyone can spot something I may have missed!
You could try changing your code to this:
myConn.Open()
Dim myCmd As New OleDbCommand
With myCmd
.Connection = myConn
.CommandType = CommandType.Text
.CommandText = "INSERT INTO Guestbook (Name,Address,Email,Comments) VALUES (#Name,#Address,#Email,#Comments)"
.Parameters.Add("#Name", OleDbType.VarChar).Value = TxtName.Text
.Parameters.Add("#Address", OleDbType.VarChar).Value = TxtAddress.Text
.Parameters.Add("#Email", OleDbType.VarChar).Value = TxtEmail.Text
.Parameters.Add("#Comments", OleDbType.VarChar).Value = TxtComments.Text
End With
myCmd.ExecuteNonQuery()
myConn.Close()
Don't put this in a Try Block. If you get an error, just post it, and we'll see what the error is.