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!
Related
I have a Guid loaded with a ID that a user selected from a GridView.
I want to pass this Guid to another page, but i dont know how to append it to the statement below:
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
Here is the full code:
Dim dvrLicense As GridViewRow
Dim guidLicense As Guid
dvrLicense = grdAllUserLicense.SelectedRow
guidLicense = StringToGUID(dvrLicense.Cells(1).Text.ToString)
Response.Redirect("LicenseDetailsView.aspx?idLicense=" guidLicense)
the variable i want to pass is called: guidLicense.
Use a format string:
Response.Redirect(String.Format("LicenseDetailsView.aspx?idLicense={0}", guidLicense))
Or perhaps just concatenate it (though the former is preferred):
Response.Redirect("LicenseDetailsView.aspx?idLicense=" & guidLicense)
The point being that there has to be some operation performed on the two values (the string literal and the variable). Putting them next to each other doesn't mean anything to the compiler. A method call with the values as arguments, or an operator between the values, will instruct the code to do something with those values.
I am having some trouble with SQLite. I used to save "time" as an int, but i now want it as a double, which is causing some problems. I remake my database everytime i try a new fix, but it has no effect. Whenever i try to save, it get the error "4 values for 3 columns". when i change it all back to an int, it works fine again. Also, if i just remove "time all togeater from the saving process, i get the error "2 values for 3 columns". I have no clue what is going on. Does a real take up two values or whats the deal?
Creating the table:
sql = "CREATE TABLE Speed (id INTEGER PRIMARY KEY AUTOINCREMENT, LanguageType VARCHAR(20), cardsetNumber INT, time REAL)";
command = new SQLiteCommand(sql, dbConnection);
command.ExecuteNonQuery();
Adding to the table:
public void SaveSpeed(int cardsetNumber, LanguageType lt, double time)
{
Open();
sql = "insert into Speed (cardsetNumber, LanguageType, time) values (" + cardsetNumber + ", '" + lt + "', " + time + ")";
command = new SQLiteCommand(sql, dbConnection);
command.ExecuteNonQuery();
Close();
}
According to Wikipedia, Denmark uses a comma as a decimal separator. Most probably, the default culture of your process is the Danish one that imposes exactly that decimal separator when converting decimal numbers to strings.
You are doing two things that you shouldn't be doing in your code, though in this case, changing one will fix the problem:
You convert a value to a string based on a culture that is not the invariant culture for any other purpose than displaying it to the user.
You are constructing an SQL query with custom values by concatenating the values unescaped into the query string.
The first means that code that does not expect to read locale-specific number formats will simply interpret your string differently than intended. In particular, that is true when reading the string on another machine (that has another default locale set), but in this case, it is simply because the SQL parser does never expect any locale-specific number formats (and, as the comma serves as the argument separator, the syntax would actually stop being well-defined unless the parser would add any further locale-specific amendments).
The second can cause really bad trouble, so you are best served by always avoiding it.
So, what is happening here? With that locale-specific conversion, the time number is converted to something like 1,2, which is interpreted by the SQL parser as two integer numbers (separated with a comma), not as one decimal number. Hence the error message about the argument count.
The first problem could be solved by explicitly specifying the invariant culture for string conversions when the result is targeted at programs rather than humans. Always do that when you, or someone else, intends to read the value back into a number type, for example, when storing it in a text-based format for computers such as CSV or XML.
As for the second issue, to insert any custom (literal) values into your SQL query, (especially, but not exclusively, those that are not hard-coded somewhere but received from user-input), parametrize your query string:
sql = "insert into Speed (cardsetNumber, LanguageType, time) values (#cardsetNumber, #lt, #time)";
command = new SQLiteCommand(sql, dbConnection);
command.Parameters.AddWithValue("#cardsetNumber", cardsetNumber);
command.Parameters.AddWithValue("#lt", lt);
command.Parameters.AddWithValue("#time", time);
This will automatically insert any quotation or escape marks to the literal values, and there is no risk of intentional or accidental SQL injection.
I am writing a code that calls a column from a dataset using a SQL query. I use two parameters to identify which rows to select. One is the ProductSerialNumber, and the other is a datetimestamp. See my SQL query below
Select TestStation FROM tblData
WHERE ProductSerialNumber = ? AND Datetimestamp = ?
In the dataset's datatable the productserialnumber is formatted as text, and the other is formatted as a date (as you would expect).
In my vb.net code, I grab the Datetimestamp from another source (don't ask why, the only thing you need to know is that it grabs a valid datetimestamp, dimensioned as a date, that matches exactly with the tblData's entry) and I use the premade query to generate a datatable. The query is a Fill query called "TestStationLookUp"
my vb.net code looks like this
Dim dt as new dataset.tbldataDataTable
Dim dta As New DataSetTableAdapters.tbldataTableAdapter
Dim ProductSerialNumber as string = "XXXXXX"
Dim DateTimeStamp as date = SomeDateVariable
dta.TestStationLookUp(dt, ProductSerialNumber, DateTimeStamp)
It is here that the code tells me:
Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.
Line 7366: dataTable.Clear
Line 7367: End If
Error: Line 7368: Dim returnValue As Integer = Me.Adapter.Fill(dataTable)
Line 7369: Return returnValue
Line 7370: End Function
I cannot understand why this error arises, as everything is dimensioned the way it should be. This exact code setup works elsewhere in my code (except it doesn't use a date), but this specific piece won't work.
Also, if I go to the dataset in my solution, I can use the "preview data" on this query and type in the EXACT same parameters (the ProductSerialNumber and DateTimeStamp that match the record in the table AND what I use in my vb code) and it will give me produce the table I want.
Can anyone assist?
This error means that you are trying to access not valid unique id "ProductSerialNumber", maybe it does not exist
Failed to enable constraints. One or more rows contain values
violating non-null, unique, or foreign-key constraints.
Instead of passing the variable that comes from dataset ,pass a valid number that you are sure it exists in database
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 cant update my database through textbox.in the case of numeric value i can update but cant with a string value.
my coding is...
SqlCommand cmdup= new SqlCommand("UPDATE [port1] SET [prt1]=#prt1 WHERE [no]= 1",cn);
cmdup.Parameters.Add("#prt1", TextBox1.Text);
cmdup.ExecuteNonQuery();
if any one know the ans: reply me
I'd recommend explicitly defining the parameter type to match the type in the DB, and passing the value to Parameters.Add as the appropriate type.
e.g. at the moment, you are passing a string typed value to Parameters.Add, and not defining the type explicitly. Therefore, it will assume the data type from the type of value supplied...so the #prt1 type will be passed in to the DB as NVARCHAR I believe.
If the prt1 field is an INTEGER for example, much safer IMHO to do something like:
cmd.Parameters.Add("#prt", SqlDbType.Int,4).Value = Int32.Parse(TextBox1.Text);
or
cmd.Parameters.AddWithValue("#prt", Int32.Parse(TextBox1.Text));
I always like to fully define the type of the parameters I pass in to SQL to rule out any potential, unexpected issues.
Check the datatype for the #prt1 to see if it is a Int value because you are setting to the same column two different values.
Parse the textBox to Integer as you want to insert a numeric value i.e. Int64.Parse("Textbox1.Text"); well with string it does have problems.
Just a wild guess: Does prt maybe only accept numeric values?