ASP.NET saving empty date value in SQL Server database with parameters - asp.net

I have a web forms application which allows to update database columns. One of the database columns is Finish Date which is of date datatype in the SQL Server database.
I use SQL query with parameters and textbox to provide the new value for the finish date.
This is a code which gets me the value of the date from a text box within the grid:
TextBox tFD = (TextBox)grdProjectUpdate.Rows[e.RowIndex].Cells[11].FindControl("proFDTextBox");
then I use a parameter:
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = tFD.Text.Trim();
to update the value using this SQL statement:
UPDATE PMSprojects SET proFD = #proFD ,...
This solution works fine whenever there is an actual date provided. However, it does not save nulls. If I provide an empty string, it is being converted into 1900-01-01 date, even though the column in the database allows nulls.
How could I solve this issue and save null to the database?

You have to write code around this to handle, and pass DbNull.Value when the value is null.
cmd.Parameters.Add("#proFD", SqlDbType.Date).Value = (tFD.Text.Trim().Length > 0) ? (object)tFD.Text.Trim() : DbNull.Value;

Related

Convert date in textboxes to date in SQL Server

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.

SQLite -> SQLite date formatting issues

I am working on migrating my old application data to a new application database. The old SQLite database has a DateTime column called DateOpened. When I look at the old data, I see this value: 2010-09-16 12:00:00
When I query it in my new (UWP) application, the query returns 1/1/0001 12:00:00 AM, which I assume is because that is DateTime.MinValue.
The result in the new database, is a DateOpened value of -62135510400. Is this storing the value in ticks or something like that? Both SQLite databases have that column as a DateTime field, so I'm not really sure why they are being stored differently.
I updated a different row with the value 1/1/2007 from a DatePicker and it is stored in the new database as 1167694105.602.
I don't necessarily mind that the new database stores the dates this way, but I am trying to figure out a way to get them to copy over properly. I tried manually setting the values in the new database, but with a normal date format (i.e. 1/1/2007), the application crashes when trying to read from the database.
Can someone tell me what I'm missing here? It's probably something simple, but I'm stumped.
EDIT
I was able to get it to read the value correctly from the old database by specifying storeDateTimeAsTicks = false. The default value apparently is true, so my new database is storing as ticks, but when trying to read as ticks from string format, it wasn't working, so it would return DateTime.MinValue.
I was able to get it to read the value correctly from the old database by specifying storeDateTimeAsTicks = false. The default value apparently is true, so my new database is storing as ticks, but when trying to read as ticks from string format, it wasn't working, so it would return DateTime.MinValue.

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

how to insert date in custom format in sql server table

recently i was working on windows based application in .net, where i have form which has field know as Joining date, which datetimepicker control, whenever user submits the form all the details goes in the sql server table, now the issue is for the date of joining field, sql server inserts its own datetime stamp, as the field is datetime type, but i want to insert the joining date as dd.MM.yyyy, so i used Convert.. like below...
CONVERT(VARCHAR(10), #JoiningDate, 104), i checked this statement in select query with #JoiningDate replaced with GetDate(), it showed me expected results but when i try to insert record, it does not insert record as expected... i am using SP, in sql server 2008, enterprise edition...
can anyone please tell me why this happening...
please reply as soon as possible as it is of utmost important.
Regards
Abbas Electricwala.
your problem may have something to do with the type of your table column. you see, if the column's type is datetime,with your convert operation, you are getting the date value the exact way you want it, but since your column type is datetime, sql will insert a datetime value to it.
you can try and change the column type to varchar(10), and see if it makes a difference.

Equivalent of RecordSet.MoveNext while Not EOF in ASP.NET

I'm using a DataReader to display informations stored in a table.
I created Two button to go to next record and to go back.
In VB6 I used this code :
While Not Recordset1.EOF
Recordset1.MoveNext
End While
In ASP.NET I didn't find a way to do like it, because DataReader hasn't the EOF property.
EDIT :
While Not Recordset1.BOF
Recordset1.MovePrevious
End While
How can I convert this last code (VB6) to ASP.NET ??
You use Read instead of MoveNext and it'll return false if there aren't any more records.
So:
While rdr.Read()
.... ' process this row
End While
Azirar, ho1 is correct in that you should use a DataTable. If you're updating after every post back and only need a single record you could still use a DataReader, but set up your SQL statement to get a single row (storing the appropriate information needed in your SQL statement (or better yet stored procedure) to get that single record back within query strings or session variables).

Resources