How can I update a database string value from a TextBox? - asp.net

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?

Related

Passing a Guid through to another page ASP.NET

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.

How can I more efficiently deal with DBNull.value in vb.net / SQL Server

I have a class type object, such as:
Private Class Car
Public Property Make As String
Public Property Model As String
Public Property Used As Boolean?
Public Property Mileage As Integer?
Public Property DateSold As Date?
End Class
I'm parsing a query string that's posted to my page that may or may not have key/value pairs for the above properties. For example, it may just be:
?Make=Toyota
I have a table in SQL Server based on the Public Properties you see above, and I'm allowing NULLS on all columns. (My real data has more fields, so this is for explanation purposes)
CREATE PROCEDURE InsertCar
#Make varchar(25),
#Model varchar(25),
etc.
I'm not setting default values in the parameters in the stored procedure above. I want to know of a cleaner way to do this from code.
For example:
The data is posted to my page... I use httputility to parse it, and I can build a new object, such as:
Dim record As New Car
record.Make = Data("make")
record.Model = Data("model")
record.Used = Data("used")
record.Mileage = Data("mileage")
record.DateSold = Data("datesold")
Afterwards, I build some parameters for my stored procedure, but here's where I think I can improve:
Dim pars As New List(Of SqlParameter)
pars.Add(New SqlParameter("#Make", If(record.Make = Nothing, DBNull.Value, record.Make))
and so on...
So you can see my ternary operators for building the parameters. Is there a cleaner way, perhaps using default values or when the class is being put together to make this cleaner?
This is more of a precision and best practice question I think. Should I be assigning DBNull.Value to the public properties? Or is how I'm doing it sufficient? Is there a cleaner way to map nullable properties?
My values from the query string are parsed into a NameValueCollection, so is there an easier way to just iterate over the ones that exist, and if not exist in the class, automatically build the parameter with DBNull.Value?
I hope my question makes sense. With a lot of data it just seems ugly with all the if/then DBNull.value, etc. I feel like I could be saving myself a step somewhere along the way. The class object is helpful for organization and is utilized in other parts of the code, or else I'd probably just build the parameters and be done with it.
You can set default values in the stored procedure parameters.
CREATE PROCEDURE InsertCar
#Make varchar(25) = null,
#Model varchar(25) = null
...
And just pass your object, if it is null/missing the stored proc will default the missing paramater value to null
pars.Add(New SqlParameter("#Make", record.Make))
The SQL table also needs to accept nulls.
Or, use the vb.net IF() operator with 2 parameters
pars.Add(New SqlParameter("#Make", If(record.Make,DBNull.Value))
Is there a VB.NET equivalent for C#'s '??' operator?

Using Date parameter in SQL query, ASP.net

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

Converting Decimal In a Label to an Integer

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!

Empty QueryString parameter

The Problem
What is the proper way to check for the foo parameter in the following url's querystring using asp.net? Is this even possible?
http://example.com?bar=3&foo
I have tried checking Request["foo"] as well as Request.QueryString["foo"] and I get null for both. I have also tried populating a List with the values from the QueryString collection but as I mention below, it does not include the value.
The Question
I understand that there is no value, but shouldn't Request["foo"] return an empty string rather than null? Is there a way to find out if a querystring key exists even if it has no value?
Notes
I found here that Request.QueryString.AllKeys includes null for blank querystring parameters.
[edit]
As stated below by James and Dreas a Regex to parse the raw url might be the best (and possibly only) approach.
Regex.IsMatch(Request.RawUrl, "[?&]thumb([&=]|$)")
You can use null as the key for the NameValueCollection and it will give you a comma-delimited list of parameter names that don't have values.
For http://example.com?bar=3&foo you would use Request.QueryString[null] and it would retrieve foo.
If you have more than one parameter name without a value, it will give you a value that is comma-delimited.
For http://example.com?bar=3&foo&test you would get foo,test as a value back.
Update:
You can actually use Request.QueryString.GetValues(null) to get the parameter names that don't have values.
Request.ServerVariables["QUERY_STRING"] will return the query string, complete, as a string. Then search it using a Regex or IndexOf
You get null because the foo parameter doesn't have a value with it.
...What's the problem exactly?
If you still want to check for its existence (although it lacks a value), try something like this:
bool doesFooExist = Request.Url.AbsoluteUri.IndexOf("foo=") >= 0 ? true : false;
Dreas is correct. Variable "bar" has a value but foo does not.
QueryString["Bar"] will return 3 because it has the value 3 associated with the variable Bar. However, Foo will return null because their is no value and when you are calling QueryString on a variable or key, you are querying for the value, not the key, so that is why you are returning null.
query string is probably a waste one. If you use Request.Params[""] or iterate it, then you will find your desired one. Its really handy than other things.
Let me know if you need any help in this.

Resources