Hi I am trying to take the amount entered in a text box and save that to a sql database in decimal format. The field in the table is set as decimal 7,2
The amount a user inputs is save to the table. However it rounds the decimal amount. eg. 10.55 saved as 11.00 & 10.45 saved as 10.00
I'm using visual studio 2010 and vb.net
This is the code I'm using to write the content to the database. Any help would be appreciated.
myCommand.Parameters.AddWithValue("customer_contribution", Convert.ToDecimal(CType(Me.FormView1.FindControl("CustomerContributionTextbox"), TextBox).Text))
I've also tried it without the Decimal conversion and end up with the same results.
myCommand.Parameters.AddWithValue("customer_contribution", customer_contribution)
Use # symbol before parameter name. and if you want to specify the parameter's sqldbtype then use the properties of command parameter as per equivalent to decimal type.
Check this:
myCommand.Parameters.AddWithValue("#customer_contribution",
Follow this Configuring Parameters and Parameter Data Types (ADO.NET)
' Add the input parameter and set its properties.
Dim parameter As New SqlParameter()
parameter.ParameterName = "#Price"
parameter.SqlDbType = SqlDbType.Decimal
parameter.Direction = ParameterDirection.Input
parameter.Value = categoryName
' Add the parameter to the Parameters collection.
command.Parameters.Add(parameter)
Related
I am working in ASP.NET as front end and SQL Server 2012 as backend. In ASP.NET, the user enters a date in 3 textboxes in the format DD/MM/YYYY.
Now I have concatenated these textbox values into a string. In SQL Server, I want to save this date into column DOB with a data type of DATE.
Below is concatenated string in ASP.net
string strDOB = txtYY.Text + "/" + txtMM.Text + "/" + txtDD.Text;
How can I now save this strDOB in SQL Server?
Stop using strings. Besides the advice in the comments to use a dedicated picker control, the next best advice is to parse those strings into integers (briefly), then construct a DateTime object from that and then do not let it get converted back into a string. It's when people let extra string/date conversions happen that they introduce formatting problems. So get the value:
var year = Int32.Parse(txtYY.Text);
var month = Int32.Parse(txtMM.Text);
var day = Int32.Parse(txtDD.Text);
var dob = new DateTime(year,month,day);
And then pass it to SQL Server:
var cmd = new SqlCommand(...);
cmd.Parameters.Add("#DOB",SqlDbType.Date).Value = dob;
And make sure that your query uses the parameter #DOB wherever you want to use that value.
Try this:
UPDATE [Table] SET [Column] = '' + strDOB + ''
Be careful, though... this hasn't been sanitized to guard against SQL Injection. I've only demonstrated the direct answer to your question, nothing more.
As a best practice, you should never concatenate together unchecked user input and store the result in a column. Techniques for preventing this are outside the scope of this Q&A, but are easily discovered with a minimal amount of searching.
--EDIT--
I defer to Damien's answer on this one. I agree with his syntax suggestions.
So, you have a recordset created like this:
Set rs = Server.CreateObject("ADODB.Recordset")
And you fill it like this:
rs.Open queryString, AuthConn, adOpenKeyset, adLockReadOnly
My question is, I want a second recordset that is a subset of the first (rs) recordset, can you do this in classic asp
Set rs2 = Server.CreateObject("ADODB.Recordset")
My immediate guess is that it would be something like this
rs2.Open queryString, rs, adOpenKeyset, adLockReadOnly
Why you ask? Well we have an older site that we are updating and adding new features too and rather than change a LOT of code I was wondering if I could be sneaky and use a setset of an already created (large) recordset, to save on another query to the db etc. Just wondering if it can be done.
Thanks,
You can use the Clone method to create a duplicate recordset, then use Filter to reduce the dataset to what you're interested in. For example:
Dim rs, rs2
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open queryString, AuthConn, adOpenKeyset, adLockReadOnly
Set rs2 = rs.Clone()
rs2.Filter = "Field1 = 'foo'"
The string form of Filter is basic; it's pretty much <Field> <op> <value>. You can combine multiple expressions using AND and OR, but even that has some limitations (see the documentation link for the full details).
For more complex filtering, you can pass the Filter property an array of Bookmark objects. In this case, you loop through the recordset (or a clone of the recordset), testing each record by whatever complex criteria you have. If the record passes the test, you save its Bookmark to an array or other collection. Then, you can set the Filter property to your array of Bookmarks and you have a custom-filtered recordset.
'Note that I haven't tested this code
Dim rs, rs2, bookmarks
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open queryString, AuthConn, adOpenKeyset, adLockReadOnly
Set rs2 = rs.Clone()
bookmarks = Array()
Do Until rs2.EOF
If rs2("Field1") = 2 * rs2("Field2") Then
ReDim Preserve bookmarks(UBound(bookmarks) + 1)
bookmarks(UBound(bookmarks)) = rs2.Bookmark
End If
rs2.MoveNext
Loop
rs2.Filter = bookmarks
' Now rs2 contains only records where Field1 = 2*Field2
You can use this same technique to get unique values (aka DISTINCT) by using a Dictionary object to store the unique key values. Doing a DISTINCT on multiple fields is a bit trickier. What I've done is the past is to combine the multiple fields using a separator that won't be in the data (such as a pipe |). That's not always possible, though.
The recordset object can be opened only by a "connection" object, you cannot replace the connection object with another recordset object as shown above, however if you modify the querystring object and open the desired subset through your own query you can achieve this.
Please post querystring if you have difficulty making the subset.
Obviously you can create a second query and recordset and run it over and over again inside "do while not rs.eof............loop" - I'm guessing that's what you want to avoid.
You might want to take a look at Datashaping. There's an article about it here. It's old, but then this is Classic ASP
https://web.archive.org/web/20210513001641/https://www.4guysfromrolla.com/webtech/092599-1.shtml
There also used to be a page on MSDN called "Using Data Shape to create hierarchical recordsets". You'll find loads of links to it on Google but they all take you to a 404 page on a resource for .net developers now :(
I have a bit of a head scratcher with the Date.Parse /ParseExact functionality in VB.
To surmise, I have an ASP.Net 4.0 app, on one of the pages there is a calendar control which the user chooses a date and time, these are fed into a string (strReqDeadline) which takes the following European / UK date time format: dd/MM/yyyy HH:mm:ss.fff
So for example the contents of strReqDeadline would be: 29/03/2013 16:30:00.000
I then need to insert this into a SQL datetime column, so obviously it needs converted from UK to the US/datetime format. I've been attempting to do this with Date.Parse and Date.ParseExact with no success. The following should work according to the research I've done:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate = As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
However, what actually happens at runtime is bizzare, the Date.ParseExact function trims off the fractal seconds from the time (as far as I can see it shouldn't be doing this because the filter specifies .fff), and otherwise leaves the entire string completely unchanged.
So, if the value of usDate is output, it appears as follows: 29/03/2013 16:30:00
What it should contain is datetime: 3/29/2013 4:30PM
The really strange thing is if I put a watch on usDate and start the app, in the development environment its value shows as #3/29/2013 4:30PM#, both in the watch list and when hovered over in the source window, but any form of output displays the original string, just minus the fractions of second, and doesn't convert to datetime.
From what I read the 'InvariantCulture' specification should negate any locale specific issues with output, but just in case this were the issue I also tried specifying an explicit local culture with System.Globalization.CultureInfo.CreateSpecificCulture("en-GB") (tried fr-FR too), but this makes no difference. The Windows regional settings on both the client and server are set to UK if this bears any relevance.
Maybe I'm missing something very obvious but I just can't see why I'm getting this output, Date.ParseExact doesn't throw any exceptions or complain about the string not being recognised, but I'm struggling to understand why it just removes the fraction seconds and does nothing else, especially since the input spring matches the specified mask exactly.
I'd be very interested to hear if anyone else has experienced an odd issue like this and what you did with it!
Thanks :)
EDIT: Full code with SQL section is as follows:
strReqDeadline = "29/03/2013 16:30:00.000"
Dim usDate As Date = Date.ParseExact(strReqDeadline, "dd/MM/yyyy HH:mm:ss.fff", System.Globalization.CultureInfo.InvariantCulture)
'SQL
Dim con As New Data.SqlClient.SqlConnection("data source=XXXXX;initial catalog=YYYYY;Integrated Security=True")
Dim cmd As New Data.SqlClient.SqlCommand()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Requests (ReqOwnerID, ReqDeadline, ReqStatus)" _
& "VALUES ('" & UserID & "', '" & usDate & "', '1')"
con.Open()
Dim NewReqID = cmd.ExecuteScalar()
con.Close()
'
Why is it you thin it is not working? These are all the same underlying date/time:
29/03/2013 16:30:00.000
29/03/2013 16:30:00
3/29/2013 4:00PM
You cannot rely on what hovering over a non-string variable shows to determine its inner value. All you are seeing is the evaluation of ToString(). If you want a String to show the fractions seconds, then you need to call ToString() and specify the format "dd/MM/yyyy HH:mm:ss.fff". By default a DateTime type if not going to show your fractions seconds when you convert to a String.
If you are not using parameters (and you should be) then your final SQL statement after injecting the DateTime would be something like this:
INSERT INTO MyTableWithDate
(column1
,column2
,MyDateCol)
VALUES
('a'
,'b'
,'20130329 16:30:00.557')
As I mentioned before, a Date datatype is not String. It's an object (or a rather a DateTime structure, by I digress). You must call the correct ToString() meth0d.
Try using this withing your SQL string:
& "VALUES ('" & UserID & "', '" & usDate.ToString("yyyyMMdd HH:mm:ss.fff") & "', '1')"
Of course, there is little point converting a string to Date object to immediately convert it back to a string again, but this code should work.
usDate is an object of type DateTime, and it appears to be storing the correct value. When you are inspecting it, you are seeing a string representation of that datetime value. It doesn't contain either 29/03/2013 16:30:00 or 3/29/2013 4:30PM, those are just two valid representations of what it contains.
You say
any form of output displays the original string
This is not true. In fact you have control over how it is output when you call ToString(), where a format can be specified
What you are doing looks correct i.e. using Date.ParseExact to convert a date in UK format to a Date type. The issue you are having is that when it displays this as a string it is displaying it in your local culture (the debugger appears to always want to display in US format), but the Date you have set is correct.
I am using C# for front end and Oracle as a database. I have a BLOB type field in a table and is used to contain images. What I actually need to do is that whenever a record in table doesn't contain any image I want to show default pic for that particular record in front end. For that purpose can I get a binary format of that default image(without saving that image with a dummy record) after saving it temporarily in database, and then using that binary format in query to show default pic when the image doesn't exists for any record. What I am getting now is :
SELECT EMP_IMG FROM Employee_Master WHERE EMP_CODE = 1234
----------------------------------------------------------
(BLOB)
Look into byte[]; use Binary Serializer to get the byte[] version of the object.
See this: C# Object Binary Serialization
Currently using VS2008, VB.NET, SQL.
I have a FormView from a Data Source that is getting some fields that are stored as Decimals in the SQL Database.
I am grabbing the field from the FormView as such:
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
I need to take this value, and convert it to an Integer, then send it along to an API. I have the API Calls done, tested and working, but I'm getting an error as when it is getting this value, the API is returning "Must be an Integer" error.
What I have tried so far:
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
Dim AvgTicket1 As Integer
AvgTicket1 = Double.Parse(AvgTicket.Text)
Do something with AvgTicket1
I have also attempted to Round the Value, then convert it and call it - no luck.
Checking the value of AvgTicket1 (Writing it out to a Label or Response.Write) shows "100", where the database value was 100.00. But the API is still getting 100.00, apparently. Any other conversion method that I've attempted states errors that the Label cannot be converted to Integer.
What are some methods I can successfully convert this value to an integer from a label?
The title of your question and the text of your question point to two different things.
Assuming you want to know how to safely convert the decimal value retrieved from the database, which is presumably the value of AvgTicketL, before calling your API you would do the following:
Create a variable of datatype Integer and use System.Int32.TryParse() to safely convert the decimal to an integer. Then pass that variable. (Code coming)
Dim testInt as Integer = -1
If System.Int32.TryParse(AvgTicketL.Text, testInt) Then
' Do something with testInt - call the API using the value
Else
' code to execute if the parse fails.
' This could be whatever you need the code to do if the value of AvgTicketL.Text can't be properly parsed into an Int value.
End If
After some fooling around this is what I was able to do to get this to work...
I took some of what David had said, and then just made a simple adjustment - I don't know why I hadn't thought of it earlier!
Dim AvgTicketL As Label = CType(frmMerchantProfile.FindControl("F10Label"), Label)
Dim AvgTicketI As Integer = "-1"
I dimmed a second variable as an int, then
AvgTicketI = CInt(AvgTicketL.Text)
From there, I just called AvgTicketI as the variable to pass to the API. Worked!
Thanks, David, for the guidance!