Select Query on Access Database in Visual Studio - asp.net

heres my code :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
ltRooms.Text = CInt(Session("numOfRooms"))
'Calculate total cost
Dim intPrice As Integer
Dim intTotal As Integer
intPrice = AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = 'RoomType')"
intTotal = intPrice * intRooms
ltPrice.Text = intTotal.ToString
End Sub
and my datasource
<asp:AccessDataSource ID="AccessDataSource1" runat="server"
DataFile="Hostel.accdb"
SelectCommand="SELECT * FROM [Bookings]"></asp:AccessDataSource>
I'm trying to store the value from the select query and then use it to work out the total price and then store it in a literal. So far I am only getting 0. No compile errors.
Does anyone one know why this isn't working?

I am consolidating the various comments into an answer for clarity and to stop the page complaining about extended discussion. This is all off the top of my head so there might be some errors in the code. It should be enough to pinpoint the problem though.
Firstly, now that I look at it again today, I think your code is just setting the SelectCommand property of the data source and not actually querying the database. I think you need to use the DataSource.Select method.
Your code might end up looking something like this:
AccessDataSource1.SelectCommand = "SELECT [Price] FROM [Rooms] WHERE ([RoomType] = '" & RoomType & "')"
Dim intPrices As List(Of Integer) = AccessDataSource1.Select(DataSourceSelectArguments.Empty)
' Now do stuff with your price data.
If the above doesn't help then I would check the value of intPrice returned by the Select call. You should also check that RoomType is set correctly.
If the wrong data is coming back from the database then you should be able to fix your SQL query to retrieve the correct data. If you need further assistance with this then please post the SQL query and the table structure.
If the correct data is coming back then check where intRooms is defined. If it is zero then your total will be calculated as zero regardless of the value of intPrice.

Related

Get child page data from master page selectedItems

I have location DropdownList in my master page. I have set control in my child page which takes properties from master page. Now I am running a query
SELECT * FROM table where city like '"+city.text+"'
here city.text gets value from master page selected cities. But my problem is it's not actually showing records as per city.text has values in it. It shows any random records.
My Code
Master Page
<asp:DropDownList ID="locationSelector" runat="server" AutoPostBack="true">
<asp:ListItem Selected>Pune</asp:ListItem>
<asp:ListItem>Delhi</asp:ListItem>
<asp:ListItem>Chennai</asp:ListItem>
<asp:ListItem>Bangalore</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
</asp:DropDownList>
Child page VB Code
Dim location As DropDownList = Page.Master.FindControl("locationSelector")
city.Text = location.SelectedItem.ToString
If Not IsPostBack Then
Try
query = "SELECT * FROM hospitals where city like '" + city.Text + "'"
Dim cmd As New MySqlCommand(query, con)
cmd.CommandTimeout = 120
Dim da As New MySqlDataAdapter(cmd)
Dim table As New DataTable
da.Fill(table)
ViewState("Data") = table
hospitals.DataSource = table
hospitals.DataBind()
Catch ex As Exception
Response.Write(ex)
End Try
End If
UPDATE
Protected Sub hospitals_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim location As DropDownList = Page.Master.FindControl("locationSelector")
city.Text = location.SelectedItem.ToString
End Sub
Sometimes it also throws TimeOut error. But most of the time It gets results but not as per selected items. What will be any other solution for this?
A couple of tips:
1) Timeout errors can happen for a number of reasons, including lots of other traffic to the site, connection pools all used up etc. I would, for a small list of cities, maybe keep that in a cache after the first call, so that you do not need to load the city list from database every time. Depending on your country, if you only have a few thousand cities, then just put it in an in-memory list.
2) You are using a "SELECT *" which is usually not really cool to other developers, nor to your code if the table contains more than just a city name. IF you write Select CityName from Table, then you will effectively have reduced the amount of data going from your database to your program, and it is clear to the other developers exactly what you're pulling from that table.
3) If you have an ID for the city, it will likely perform even better as string matcing is REALLY slow compared to matching a couple of ID's. I've seen 20% speed improvements by replacing strings with constants, you wouldn't believe how slow strings are in code these days.
4) Last, and I think you may already have done this, make sure that you INDEX every field that you do a WHERE filter on. If you search for Hospitals, then make sure that the Hospitals.City field is indexed to avoid row lookups.
I hope (any) of this helps you :)
As per my understanding you need to change below
to fetch the selected TEXT value use location.SelectedItem.Text instead of location.SelectedItem.ToString()
city.Text = location.SelectedItem.Text // change here
before binding the dropdown control check the no. of rows
if(table.Rows.Count>0)
{
hospitals.DataSource = table;
hospitals.DataBind();
}
I would suggest to use prerender event within page. In prerender event try to access your master page control and get value.

Adding duplicate rows of data to my access database

Hey there Im having difficulties adding a single row of data to my database when I submit my form it insert two rows of data to my mdb database any suggestions samples or help will work ill really appreciate it Thanks
Protected Sub Button3_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim conCoaxis As OleDbConnection
Dim strInsert As String
Dim cmdInsert As OleDbCommand
conCoaxis = New OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\site\App_Data\sabersolutions.mdb")
strInsert = "INSERT INTO register (Name, Email, Newsletter) Values (?, ?, ?)"
cmdInsert = New OleDbCommand(strInsert, conCoaxis)
cmdInsert.Parameters.Add("#Name", OleDbType.VarWChar, 255).Value = txtName.Text
cmdInsert.Parameters.Add("#Email", OleDbType.VarWChar, 255).Value = txtEmail.Text
cmdInsert.Parameters.Add("#Newsletter", OleDbType.Boolean, 1).Value = ckNews.Checked
Try
conCoaxis.Open()
cmdInsert.ExecuteNonQuery()
conCoaxis.Close()
Response.Write("Updated Successfully!<p> </p><p> </p><p> </p>")
Catch
conCoaxis.Close()
End Try
Your code looks fine. It looks to me more like you have the sub-routine Button3_Click assigned as the handler more than once. For example in the aspx page you have something like
<asp:Button runat="server" ID="Button3" Text="Submit" OnClick="Button3_Click" />
See the OnClick attribute? that wires the click event to call Button3_Click
Then somewhere else, possibly in Page_Load in the .vb code-behind, you also have:
AddHandler Button3.Click, AddressOf Me.Button3_Click
So ONE click event will end up calling the same function twice. Get rid of the AddHandler code you don't need to manually wire-up click handlers, it's done for you.
If that's not your problem you may of course be clicking your button twice, this is a well known issue with HTML forms. You can Google many solutions. My preferred solution is to always do a 'SELECT' first to check if the record already exists, or wrap your insert command in a 'IF NOT EXISTS' (I think this works for MS Access, I know it dows for MS Sql Server)
strInsert = "IF NOT EXISTS (SELECT 1 FROM register WHERE Name = #Name AND Email = #Email AND Newsletter = #Newsletter) BEGIN INSERT INTO register (Name, Email, Newsletter) Values ( #Name, #Email, #Newsletter) END"
Another option is:
strInsert = "INSERT INTO register (Name, Email, Newsletter) SELECT TOP 1 #Name, #Email, #Newsletter FROM register WHERE NOT EXISTS (SELECT 1 FROM register WHERE Name = #Name AND Email = #Email AND Newsletter = #Newsletter)"
This latter statement only works if 'register' has at least one record in it, MS Access Jet database requires a table name in the statement, see here for more info. Seriously though, drop Access and use a proper database like SQL Server, then you can use the first statement directly or via a stored procedure a much more professional solution.

Msaccess 2010 -base on a report on a recordsource

I have looked at a previous example of yours detailed below. However I have a problem:
Heres my code it runs off a button on a form called Reports:
Dim dbs As Database
Dim qdf As QueryDef
Dim varitem As Variant
Set dbs = CurrentDb()
Set qdf = dbs.QueryDefs("Qry_rpt_cr")
qdf.Parameters(0) = Forms!frm_reports.rmselectfilter.Column(1, varitem)
qdf.Parameters(4) = Forms!frm_reports.rmselectperiod.Column(0, 0)
qdf.Parameters(3) = Forms!frm_reports.rmselectperiod.Column(0, 1)
qdf.Parameters(2) = Forms!frm_reports.rmselectperiod.Column(0, 2)
qdf.Parameters(1) = Forms!frm_reports.rmselectperiod.Column(0, 3)
Set grst = CurrentDb.OpenRecordset("Select * from Qry_rpt_cr")
DoCmd.OpenReport "rpt_cr_test", acPreview
grst.Close
Set grst = Nothing
End Sub
The question is the query needs five parameters to be passed to it and then open the recordset using the defined parameters and then open the report. But the code does not open. Its says an error on this line Set grst = CurrentDb.OpenRecordset("Select * from Qry_rpt_cr") asking for 5 parameters but I have passed them earlier in the code. Any suggestions would be welcomed. HAppy to make a donation for a correct answer. ED
Example from your archives
From Access Web you can use the "name" property of a recordset. You resulting code would look something like this:
In the report
Private Sub Report_Open(Cancel As Integer)
Me.RecordSource = gMyRecordSet.Name
End Sub
In the calling object (module, form, etc.)
Public gMyRecordSet As Recordset
'...
Public Sub callMyReport()
'...
Set gMyRecordSet = CurrentDb.OpenRecordset("Select * " & _
"from foo " & _
"where bar='yaddah'")
DoCmd.OpenReport "myReport", acViewPreview
'...
gMyRecordSet.Close
Set gMyRecordSet = Nothing
'...
End Sub
I've not used Access for a while , but i think you are setting the params for a query, and then running a different query. Access is asking for params to be provided for the query you are asking ("select * from ..."), not the (named) query that your query references, if that makes sense.
This should be easily fixed, just run OpenRecordset from the QueryDef:
Set grst = qdf.OpenRecordSet
and then Access will include the query's params correctly.
Edit: Thx Remou

Inserting null values into date fields?

I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function

MySQL Output parameter with asp.net and SqlDataSource control

I'm in the process of switching my application from MSSQL to MYSQL. When I was using MSSQL, I retrieved the last auto increment value via
Private Sub dsImpoundInformation_Inserted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles dsImpoundInformation.Inserted
_impoundId = e.Command.Parameters("impoundId").Value
End Sub
Private Sub dsImpoundInformation_Inserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceCommandEventArgs) Handles dsImpoundInformation.Inserting
Dim impoundIdparam As New SqlClient.SqlParameter()
impoundIdparam.ParameterName = "impoundId"
impoundIdparam.Direction = System.Data.ParameterDirection.Output
impoundIdparam.DbType = DbType.Int32
impoundIdparam.Value = 0
e.Command.Parameters.Add(impoundIdparam)
End Sub
and
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = SCOPE_IDENTITY();"
Now when i try
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET #impoundId = LAST_INSERT_ID();"
i get the error:
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near '0 = LAST_INSERT_ID()' at line 1
And when i try:
InsertCommand="INSERT INTO LotManager_impounds (accountId, truckId, createdBy, driver, locationId, dateArrived, towedFrom, reasonForImpound, reasonForImpoundOther, impoundCity, impoundCounty, timeOfImpound, dateDeemedAbandoned, ticketNumber) VALUES (#accountId,#truckId,#createdBy,#driver,#locationId,#dateArrived,#towedFrom,#reasonForImpound,#reasonForImpoundOther,#impoundCity,#impoundCounty,#timeOfImpound,#dateDeemedAbandoned,#ticketNumber); SET impoundId = LAST_INSERT_ID();"
I get the error:
Unknown system variable 'impoundId'
ultimately, I'm just trying to get the last auto increment value but there are other sections of my code in other applications that I plan on switching to MYSQL that depend on output parameters. I have't yet explored using stored procedures but at this time I would like to get this to work in a similar fashion to how I had it with MSSQL.
Thanks in advance.
Finally I broke down and decided to use stored procedures. This is the best way to do it any ways and makes the code a lot cleaner. For anyone that's encountering this same problem my advice to you would be don't waste you time trying to make it work and just use a stored procedure.

Resources