convert an empty string (from textbox) to null using ASP.NET - asp.net

if I don't enter anything in one of the textbox , ASP.NET can't tell an empty textbox and treat it at null... So anyone please help me how to detect an empty textbox and set that to null
i know that this code is ganna work well
If MUSIC_TITLE.Text.Trim() = "" Then
MUSIC_TITLE.Text = Nothing
End If
but i can't use be couse i have a lot of forms in my application so i need somthing or any function exist in the ASP.NET that can handel this
and thats for the insert in a requet the sql server
"insert into Reunion values(" & Convert.ToInt32(ID_Reunion.Text) & ",'" & d.ToString("MM/dd/yyyy") & "'," & Convert.ToInt32(ID_Membre.Text) & ",'" & Type_Reunion.Text & "','" & Session("Nom_GIAC") & "')"
and tnks

This sounds like you're trying to directly store the textbox values in your database.
Please don't do this. If you haven't already, learn about the high risk security threat of SQL Injection and parameterize your INSERTS and UPDATES.
Before setting the parameters, you can convert empty strings to Nothing if required.
Dim musicTitle as String = _
If(String.IsNullOrWhiteSpace(MUSIC_TITLE.Text), Nothing, MUSIC_TITLE.Text)

In your insert sp should be like:
create procedure Insert(#test varchar(50)=NULL)
as
begin
update foo set testCol=#test
end
In c#, use below code, when calling the sp and adding the parameters:
if(txt.Text!=String.Empty)
{
cmd.Parameters.Add("#test",SqlDBType.Varchar,20).Value=txt.Text;
}

Related

vb.net string concat adds vbCrlf literal to the string

I am trying to build a string that includes a newline character and is getting the weirdest result. This string is going to be stored in a SQL database to be later used as part of an email. My code is the following:
Dim strBody As String = "Andy," & Environment.NewLine
When I inspect the value of strBody during a debugging session, it is the following:
"Andy," & vbCrlf
I am obviously expecting is to be more like:
"Andy,"
Knowing that what is after the , is a hidden character.
Ultimately, the problem is... when I include strBody as part of my SQL insert statement, it literally shows up as the following within my SQL insert statement:
'Andy," & vbCrLf & "'
I was using this code yesterday and it worked fine. I am using similar code within another function of the same asp.net project and it works fine. I have tried using + instead of &, I have tried to use vbCrLf instead of Environment.NewLine, I have tried using stringbuilder, I have tried using string.concat. All with the same results where the & vbCrLf is included in strBody.
Is there a setting that I accidentally changed?
I know this is a weird one... Any help is greatly appreciated.
This is only Visual Studio showing you that there is new line character (vbCrLf or Environment.NewLine). If you use that string anywhere, it will be stored correctly.
I believe you will need to use some combination of Char(10) and Char(13):
Dim strBody As String = "'Andy,'" & " + CHAR(13)+CHAR(10) + "
There is a discussion about these and other methods on this thread.
You can do like this if you just need to insert Environment.NewLine inside database.
Dim a As String = """ & Environment.NewLine & """
Dim strBody As String = String.Format("Andy,{0}", a)
'"Andy," & Environment.NewLine & ""

Date changes to a vastly different value when saved into database

I'm trying to enter a date that's in a textbox into a column of datetime type
The code is as follows
txtbookissue_date.Text = DateTime.Now.Date
txtbookreturn_date.Text = DateAdd(DateInterval.Day, 7, DateTime.Now.Date)
When I Insert these two values into a database, (insert into book....) values such as 17-02-1984 show up in the database rather than, say, 26-2-2015.
I did a little research and found out that SQL interprets it as "26 minus 2 minus 2015" rather than as a date.
Printing Date(txtbookissue_date.Text) gives correct results, the only problem is saving it into the database.
The solution for this was apparently to enclose the date in single quotes, i.e '26-2-2015' rather than just 26-2-2015, Since I'm using a date function I decided to change
txtbookissue_date.Text = DateTime.Now.Date
to
txtbookissue_date.Text= "'"+DateTime.Now.Date+"'"
but It returns an error, something similar to 'cannot convert varchar type to date type, out of range exception'
How do I fix this? any help would be appreciated.
txtbookissue_date.Text = DateTime.Now.Date
txtbookreturn_date.Text = DateAdd(DateInterval.Day, 10, DateTime.Now.Date)
Protected Sub btn_issue_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btn_issue.Click
con.Open()
cmd.CommandText = "insert into Book (book_id, book_name, book_author,publisher,mem_id,mem_name,issue_date,return_date) values('" & txtbookissue_id.Text & "','" & txtibookssue_name.Text & "','" & txtbookissue_author.Text & "','" & txtbookissue_publi.Text & "','" & txtbookissue_memid.Text & "','" & txtbookissue_memname.Text & "'," & txtbookissue_date.Text & "," & txtbookreturn_date.Text & ")"
cmd.Connection = con
cmd.ExecuteNonQuery()
con.Close()
Response.Redirect("Welcome.aspx")
End Sub
you are inserting date as a text. I mean while you need to insert it '2015-02-26' you are trying to insert it with another format. In fact you should use parameters with your sql query. Your sql statement should be something like that
insert into Book (book_id, book_name, book_author,publisher,mem_id,mem_name,issue_date,return_date) values(#book_id, #book_name, #book_author,#publisher,#mem_id,#mem_name,#issue_date,#return_date)
Before executing query you should set parameters in command object.
cmd.Parameters.AddWithValue("#return_date", DateAdd(DateInterval.Day, 10, Date.Now.Date))
For more information about using parameters with access you can take a look here
First of all, I would highly suggest using Paramaters.
Second, since you want to format your date into a string that is not the default culture. I would suggest you use String.Format() or ToString() (examples).
Since your database most likely expects a datetime. You could parse the string back to a DateTime using DateTime.ParseExact. Look at this answer for a howto.
Let me know if this helps, if not you need to supply us with more info.
You are putting string in a DateTime column, please convert the values back to their original types before putting them in the database.
DateTime issueDate = DateTime.Parse(txtbookissue_date.Text);
DateTime returnDate = DateTime.Parse(txtbookreturn_date.Text);

string with 's not getting inserted with insert statement

I am trying to insert a question in database with field in table as nvarchar(max) (sql server 2008 r2)
Code is as follows:
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
when i insert any string with :
what's your name?
then it gives me error:
Incorrect syntax near 's'. Unclosed quotation mark after the character string ')'.
If i simply supply string as:
What is your name?
Then it does not gives me error.
Please help me.
You should be using parameterised queries if possible since simple string insertion directly into a query will, as you have seen, possibly corrupt the query.
In other words, if the text box contains Paddy O'Rourke, your query becomes:
open close what the ?
| | |
insert into QuestionMaster values('Paddy O'Rourke') ...
and you can see the fact that the embedded ' is corrupting the query.
It will also, as you have yet to realise, allow people to perform SQL injection attacks on your database since you're not sanitising the input.
If, for some reason, your shop disallows parameterised queries (as it appears from one of your comments), find another place to work. No, just kidding, but in the presence of such a bone-headed policy, you'll need to sanitise the input yourself.
But that's fraught with danger, I would first try to change such a policy, laying out in no uncertain terms the risks involved.
Well, you should rather make use of Parameterized queries.
This will also avoid SQL Injection.
There may be a chance that your data may contain some special characters like single quotation mark which make your statement fail.
So better to use parameterized query: Parameterized queries do proper substitution of arguments prior to running the SQL query.
SqlCommand insertNewAreaPath = new SqlCommand(
"insert into QuestionMaster (Question, ClientID, KioskID) VALUES(#Question, #ClientID, #KioskID)", con);
insertNewAreaPath.Parameters.Add("#Question", txtQuestion.Text);
insertNewAreaPath.Parameters.Add("#ClientID", ViewState("ClientID"));
insertNewAreaPath.Parameters.Add("#KioskID", ViewState("KioskID"));
insertNewAreaPath.ExecuteNonQuery();
ELSE: use .Replace("'", "''")
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
You could escape single quote by replacing single quote (') with two single quotes ('') in the txtQuestion.Text.
Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
gc.ExecuteCommand("insert into QuestionMaster values('" & txtQuestion.Text.Replace("'", "''") & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')")
Response.Write("<script type='text/javascript' language='javascript'>alert('Question Added Sucessfully!!!')</script>")
BindGrid()
End Sub
Replace ' with '' and it will work fine.
Try this
what''s your name?
//declare this variable
String sql="insert into QuestionMaster values('" & txtQuestion.Text & "','" & ViewState("ClientID") & "','" & ViewState("KioskID") & "')";
debug it and you will find where it appears problem.

How to get the insert ID from this ADODB.Recordset?

I'm trying to avoid using straight SQL queries in my web app. I looked around and have come to the conclusion that ADO Recordsets would be the best or at least safest tool for the job. I need to insert records into a database table. Unfortunately I'm at a loss as to how to get the identity value for the record which was just inserted. Here's a reduction of what I've got now:
<%
dim insertID, rs
set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "my_table_name", conn, adOpenForwardOnly, adLockOptimistic
rs.AddNew()
Call m_map_values_to_rs(rs)
rs.Update()
insertID = rs("id")
rs.Close()
rs = Nothing
%>
The code I have is successfully inserting the record, but I can't for the life of me figure out how to get the id field of the Recordset to update after the insert. How can I get the identity column value back from this Recordset?
UPDATE - Here's the solution with regard to the code above.
I had to change the cursor type to adOpenKeyset instead of adOpenForwardOnly. After I did this the record is automatically updated with the "auto number" field's new value after the insert. However it is not what you think it is. The value of rs("id") doesn't become an integer or even a variant. It becomes some sort of Automation type and cannot be evaluated as a number. Nor can CInt() be used directly on that type for some reason. So what you must do is to convert the value to a string and then convert it to an Int. Here's how I managed that:
insertID = CInt( rs("id") & "" )
Thanks to Dee for their answer. It helped immensely.
This article explains the means of getting identity value with example code.
The relevant code snippet is:
<%
fakeValue = 5
set conn = CreateObject("ADODB.Connection")
conn.open "<conn string>"
sql = "INSERT someTable(IntColumn) values(" & fakeValue & ")" & _
VBCrLf & " SELECT ##IDENTITY"
set rs = conn.execute(sql)
response.write "New ID was " & rs(0)
rs.close: set rs = nothing
conn.close: set conn = nothing
%>

Classic ASP: Execute 2 Update Statements in single function

I am writing Classic ASP program.In one function, I have to use 2 update statements to one table in one function. First Statement is update the quantity of invoice and second update statement is base on that update Purchase Order quantity and Purchase Requisition quantity, I need to update one flag field. Can I write in same function as following:
SET RS = app.Execute("SELECT PRInvoiceNo, Quantity FROM PurchaseOrderDetails WHERE CoID='" & param & "'")
do while RS.EOF=false
app.Execute("UPDATE PurchaseRequisitionDetails SET PO_Quantity = PO_Quantity + " & RS("Quantity") & " WHERE CoID='" & param & "' AND PRInvoiceNo = '" & RS("PRInvoiceNo") & "'")
app.Execute("UPDATE PurchaseRequisitionDetails SET FullyPaidFlag=CASE WHEN PO_Quantity >= Quantity THEN 1 ELSE 0 END WHERE CoID='" & param & "' AND PRInvoiceNo = '" & RS("PRInvoiceNo") & "'")
RS.MoveNext
loop
The problem is in the loop the first statement is properly worked. Second one not work. What can it be? Can I do like this or not?
Well, I have to go, but be sure to check the following:
Response.Write(RS.RecordCount) -- are there any records? Or, do a Response.Write("hello") inside the loop to make sure.
Check that RS("Quantity"), param, etc are not null. If they are, your string concatenation will result in a null string.
Also, please, please don't forget to escape your variables!
Replace(param, "'", "''")
Good night!

Resources