Add datagrid columns to database? - vb.net

I'm trying to add a users selected row to the database
I want the CarID, CarBrand, And CarModel to enter
When the user selected that row they click a button to add it to the database
I seem to be getting errors and I'm not sure why
Here is my code
Private Sub Btn_addtorental_Click(sender As Object, e As EventArgs) Handles Btn_addtorental.Click
If datcarsearchresults.SelectedRows.Count = 1 Then
Dim SelectedCarID As Integer = datcarsearchresults.SelectedRows(0).Tag
Dim SelectedCarBrand As String = datcarsearchresults.SelectedColumns(1)
Dim SelectedCarModel As String = datcarsearchresults.SelectedColumns(2)
PublicCarID = SelectedCarID
If DbConnect() Then
Dim SQLCmd As New OleDbCommand
With SQLCmd
.Connection = cn
.CommandText = "Insert into Tbl_Rental (CarID,CarBrand,CarModel) " & "Values (#CarID,#CarBrand,#CarModel)"
.Parameters.AddWithValue("#CarID", SelectedCarID)
.Parameters.AddWithValue("#CarBrand", SelectedCarBrand)
.Parameters.AddWithValue("#CarModel", SelectedCarModel)
.ExecuteNonQuery()
It says it cannot be converted to string??
Any help would be appreciated thanks

Where is it erroring? I'm guessing when you try to get the value from the column. The SelectedColumns(1) doesn't bring back a string but brings back a DataGridViewColumnCollection. Take a look at this link with more answers. vb.net how to get cell value from datagridview.

Related

How i can get max value with a condition in within datatable VB.NT

I have datatable named (Dt)
Has 2 column ("Type","value").
How i can get max value where tybe = textbox1.text ____
in (datatable)ADO.net not SQL server
Thank you
Ok, so lets assume two buttons.
First button to load the data table form SQL server
(that you suggest/note you already have the data table).
next, we have a text box for user to enter the column name.
And then a button get max, which will use the text box with column name.
After that, we have a text box to show the results.
So, we have this code:
Dim rstData As New DataTable
Private Sub cmdLoadData_Click(sender As Object, e As EventArgs) Handles cmdLoadData.Click
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
"SELECT * FROM tblhotelsA ORDER BY HotelName"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
rstData.Load(cmdSQL.ExecuteReader)
MsgBox("Data loaded", MsgBoxStyle.Information)
End Using
End Using
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If rstData.Rows.Count > 0 Then
' find max colum based on colum name in
Dim MyResult As Object
MyResult = rstData.Compute($"MAX({txtColumn.Text})", "")
Debug.Print(MyResult.ToString())
txtMax.Text = $"Max value for colum {txtColumn.Text} = {MyResult.ToString()}
-- colum data type = {MyResult.GetType.ToString()}"
End If
End Sub
and the results are now this:
Edit: User wants to build a sql query to get the max value
Ok, so the question is NOT that we have a data table (dt) in code, and we wish to pull/get/find the max value from that vb.net dt.
our question is that we want to query the database for a given column, and PUT THE RESULTS into that vb.net data table.
So, we want to QUERY SQL server to get the one result.
So, a very different goal.
This would be a "more common" question, and thus amounts to a plain jane SQL query.
this also of course will perform MUCH faster, since we don't pull nor have that vb.net "dt" or datatable, but we are to put the results of the sql query into that dt.
So, our form can look the same, but now our code for the "Get max" button would be this:
We do NOT require the first button to "load data" anymore.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
$"SELECT MAX(#P1) FROM tblhotelsA"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#P1", SqlDbType.NVarChar).Value = txtColumn.Text
rstData.Load(cmdSQL.ExecuteReader)
txtMax.Text = $"Max value for colum {txtColumn.Text} = {rstData.Rows(0)(0).ToString()}"
End Using
End Using
Now, say we want to "ask" the user for a given city, and then return the max found age for that user supplied city.
Then this:
Using conn As New SqlConnection(My.Settings.TEST4)
Dim strSQL As String =
$"SELECT MAX(Age) FROM tblhotelsA WHERE City = #City"
Using cmdSQL = New SqlCommand(strSQL, conn)
conn.Open()
cmdSQL.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtWhatCity.Text
rstData.Load(cmdSQL.ExecuteReader)
txtMax.Text = $"Max age found for city = {txtcity.Text} = {rstData.Rows(0)(0).ToString()}"
End Using
End Using

Select from multiple tables without getting Parameter error

I am currently trying to code a database project for a musicians record log. I have been struggling to join 3 tables together in a single search of the database and I am getting this error:
No value given for one or more required parameters.
I have been searching online for why this is but cannot find anything which quite fixes my code. I have tried copying almost word for word other syntax but still get this error. Any help would be much appreciated, my database is as follows:
Program(ProgramID(PK), LengthOfProgram, UserName, NameOfProgram)
ProgramList(PieceListID(PK), PieceID(FK), ProgramID(FK))
Repertoire(PieceID(PK), NameOfPiece, Composer)
Those are the fields needed from repertoire.
Here is my code for when the the program is selected from the list box.
Public dtbConnecter As New OleDbConnection
Dim fileLocator As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source = " + Application.StartupPath + "\Musician Record Log.accdb"
Private Sub lstPro_SelectedIndexChanged(sender As Object, e As EventArgs) Handles lstPro.SelectedIndexChanged
Dim programID As String
Dim programIDLength As Integer
Dim selectedString As String = lstPro.GetItemText(lstPro.SelectedItem)
programIDLength = selectedString.IndexOf(":")
programID = selectedString.Substring(0, programIDLength)
MsgBox(programID)
Dim SQL As String = "Select Program.ProgramName, Program.ProgramLength, Repertoire.NameOfPiece, Repertoire.Composer From ((ProgramList INNER JOIN Repertoire ON ProgramList.PieceID = Repertoire.PieceID) INNER JOIN Program ON ProgramList.ProgramID = Program.ProgramID) WHERE (Program.ProgramID = #Param1)"
Dim da As New OleDbDataAdapter
Dim dtbTable As New DataTable
Dim ds As New DataSet
Dim dtbCommand As New OleDbCommand
dtbCommand.Parameters.Add("#Param1", OleDbType.VarChar).Value = programID
dtbCommand.Connection = dtbConnecter
dtbCommand.CommandType = CommandType.Text
dtbCommand.CommandText = SQL
da.SelectCommand = dtbCommand
da.Fill(dtbTable)
'Here i would then use the table's information to update my form, however first i'm trying to get this to work.
da.Dispose()
da = Nothing
End Sub
I also import System.Data, System.Data.OleDb and System.Drawing.Imaging at the top.
It was just a stupid mistake, the names of the fields in the database are NameOfProgram and LengthOfProgram but in the SQL query I used ProgramName and ProgramLength, thanks for all the help in ensuring the SQL query was correct and I did need to correct the data type but the main problem was the wrong identifier.

VB.net Query wont retrieve data from access database

I have created a query using vb.net with parameters which should allow the query to retrieve data from my access database but however when I click on the button it only shows blank fields but no rows are retrieved from the database. Could you please help me what I am currently doing wrong.
Imports System.Data.OleDb
Public Class RouteToCruise
Private Sub RouteToCruise_Load(sender As Object, e As EventArgs) Handles MyBase.Load
End Sub
Private Sub Route_Btn_Click(sender As Object, e As EventArgs) Handles Route_Btn.Click
Try
Dim row As String
Dim connectString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\DeepBlueTables.mdb"
Dim cn As OleDbConnection = New OleDbConnection(connectString)
cn.Open()
Dim CruiseQuery As String = "SELECT Route.RouteName + ', ' + Cruise.CruiseID As CruiseRoute FROM Route INNER JOIN Cruise ON Route.RouteID = Cruise.RouteID WHERE CruiseID = ?"
Dim cmd As New OleDbCommand(CruiseQuery, cn)
'cmd.Parameters.AddWithValue("CruiseID", OleDbType.Numeric).Value = Route_Txt.Text
cmd.Parameters.AddWithValue(("CruiseID"), OleDbType.Numeric)
Dim reader As OleDbDataReader = cmd.ExecuteReader
'RCTable.Width = Unit.Percentage(90.0)
RCTable.ColumnCount = 2
RCTable.Rows.Add()
RCTable.Columns(0).Name = "CruiseID"
RCTable.Columns(1).Name = "RouteName"
While reader.Read
Dim rID As String = reader("RouteID").ToString()
cmd.Parameters.AddWithValue("?", rID)
row = reader("CruiseID") & "," & ("RouteName")
RCTable.Rows.Add(row)
End While
reader.Close()
cn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
If the user enters route name in the text box then the rows should show cruise ID and route name for each of the selected routes. for example if users enters Asia in the text box, clicks on the button then the query should return the cruiseID for the cruises which are going to Asia.
Your use of parameters makes no sense. First you call AddWithValue and provide no value, then you execute the query and then you start adding more parameters as you read the data. Either you call AddWithValue and provide a value, or you call Add and then set the Value on the parameter object created. Either way, it MUST be before you execute the query or it's useless.
myCommand.Parameters.AddWithValue("#ParameterName", parameterValue)
or
Dim myParameter = myCommand.Parameters.Add("#ParameterName", OleDbType.Numeric)
myParameter.Value = parameterValue

How to update a MS Access database in vb.net

Hi I'm having trouble with updating one of my tables using vb.net when i click on the button to update the data base it give me the error "System.Data.OleDb.OleDbException: No value given for one or more required parameters."
here is the code
Protected Sub Button6_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim aConnection As New OleDbConnection
Dim aCommand As New OleDbCommand
Dim SQLQuery, aConnectionString As String
Dim Text As String = TextBox1.Text
Dim aDataAdapter As New OleDbDataAdapter
Dim aDataReader As New DataSet
SQLQuery = "Update Review Set report='Yes' Where Text='" & Text & "'"
aConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Server.MapPath("App_Data/BookReviewWebsite.accdb")
aConnection = New OleDbConnection(aConnectionString)
aConnection.Open()
aCommand = New OleDbCommand(SQLQuery, aConnection)
aCommand.ExecuteNonQuery()
Label15.Text = "Review has been reported"
aConnection.Close()
End Sub
Review, Report and Text. Here you have two fields and a table name, you should check if your database effectively contains a table named Review and if, in this table, there are two field named report and Text.
If your really have this table and these fields, then you need to enclose the word TEXT with square brackets because the word TEXT is a reserved keyword in Access 2007.
Last, but not least of your problems is the query string itself. Concatenating strings in that way could be a source of errors. If you have a single quote in your 'Text' variable then the results could be impredictable and range from Syntax error to Sql Injection
SQLQuery = "Update Review Set report='Yes' Where [Text]=?"
aCommand = New OleDbCommand(SQLQuery, aConnection)
aCommand.Parameter.AddWithValue("#p1", Text)
aCommand.ExecuteNonQuery()

How do I add htmltablecell data to database after I click submit

I created an htmltable in .aspx.vb, because I have a lot of rows that come from database and they depend on the querystring. that part is fine. But when someone makes a change in one of the cells how do I save data back to database?
Code -
Dim tr As New HtmlTableRow
Dim td As New HtmlTableCell
td = New HtmlTableCell
Dim txtbox1 As New TextBox
txtbox1.ID = "price_" & rd("id")
txtbox1.Text = rd("price")
td.Controls.Add(txtbox1)
tr.Cells.Add(td)
tb1.Rows.Add(tr)
Now when someone changes the price in the textbox, how do I save it in database?
This is code for submit button -
Protected Sub submit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles submit.Click
Dim sqlcnn As SqlConnection = Nothing, sqlstr As String = "", sqlcmd As SqlCommand
sqlstr = "UPDATE ???"
sqlcmd = New SqlCommand(sqlstr, sqlcnn)
sqlcmd.ExecuteScalar()
End Sub
Please answer in detail.
I would suggest using the built in grid controls. Here is a walkthrough Walkthrough: Editing and Inserting Data in Web Pages with the DetailsView Web Server Control
. It might be better to start with Walkthrough: Basic Data Access in Web Pages.
If you choose to move forward with HTML then here is one way to do it based on what you provided. You can add an update button and try this code in that event:
'Create an update Command with the apropriate paramaters'
Dim sql = ("UPDATE SO_Prices SET Price = #Price WHERE ID = #ID")
Dim Cmd As New SqlCommand(sql, connection)
Cmd.Parameters.Add("#Price", SqlDbType.SmallMoney)
Cmd.Parameters.Add("#ID", SqlDbType.Int)
connection.Open()
'Loop through the fields returned'
For Each Key As String In Request.Form.Keys
'Make sure you only process fields you want'
If Key.StartsWith("price") Then
'Pull the ID out of the field name by splitting on the underscore'
' then choosing the second item in the array'
Dim ID As String = Key.Split("_")(1)
'Update the paramaters for the update query'
Cmd.Parameters("#ID").Value = ID
Cmd.Parameters("#Price").Value = Request.Form(Key)
'Run the SQL to update the record'
Cmd.ExecuteNonQuery()
End If
Next
connection.Close()
Let me know if you need any additional assitance. If not, please mark this as the correct answer.