unhandled exception error won't allow me to insert data - asp.net

So if i run this code i'm thrown a multi-part identifier errorregarding the binding of the textbox "clid"
Can somebody please help to resolve this issue?
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = Convert.ToString(clid)
Dim sqlentry1 As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID) VALUES("
Dim sqlentry2 As String = entrclientid
Dim sqlentry3 As String = ")"
Dim sqlentry4 As String = sqlentry1 & sqlentry2 & sqlentry3
Dim cmdclientid As New SqlCommand(sqlentry4, cnnentry)
cnnentry.Open()
string1 = cmdclientid.ExecuteNonQuery()
cnnentry.Close()
End Using
Thanks in advance
P.S. please excuse the naming conventions i wrote this extremely quickly

You don't want to convert the TextBox to a String but it's Text property:
change
entrclientid = Convert.ToString(clid)
to
entrclientid = clid.Text
But more important, you should use sql-parameters to prevent sql-injection.
Dim sql As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID) VALUES(#CLIENT_ID)"
Dim cmdclientid As New SqlCommand(sql, cnnentry)
cmdclientid.Parameters.AddWithValue("#CLIENT_ID", clid.Text)

Related

How to find the value of a dropdownlist using FindControl?

I am working on a website with VB.NET and ASP.NET. I currently have recurring DropDownLists for the user to provide input.
The design is recurring. These DropDownLists get their values from a database table, Everything with the Web interface is working except for writing these recurring values to the database - that is just to give you some background.
I have set the ID's of each DropDownList like so:
FrequencyList.ID = String.Concat("FreqList", DBReader(0))
That is in a loop while reading the DatabaseReader.
This is what I'm having issues with (please note I simplified the code down to make it easier to read:
Dim i As Integer
DBCommand = New SqlCommand()
DBCommand.Connection = DBConnection
DBCommand.CommandType = Data.CommandType.StoredProcedure
DBCommand.CommandText = "StoredProcedureName"
DBConnection.Open()
For i = 1 To AspectTableLength
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = FindControl("FreqList" & Convert.ToString(i))
ParamFrequencyID.Direction = ParameterDirection.Input
Next
The FindControl("FreqList" & Convert.ToString(i)) variable is incorrect because it does not access the value - and adding .SelectedItem.Value does not work.
I got help from a developer.
Dim MyControls As ControlCollection = Panel.Controls
Dim Number As Integer 'this is the same as "DBReader(0)"
For Each MyControl As Control In MyControls
If MyControl.ID Is Nothing Then
Else
If MyControl.ID.StartsWith("Span") Then
Number = Replace(MyControl.ID, "Span", "")
Dim Freq As DropDownList = PanelMain.FindControl(“FreqList” & Number)
Dim ParamFrequencyID As SqlParameter = DBCommand.Parameters.Add("#nFrequencyID", SqlDbType.Int)
ParamFrequencyID.Value = Freq.SelectedIndex
ParamFrequencyID.Direction = ParameterDirection.Input
DBCommand.ExecuteNonQuery()
DBCommand.Parameters.Clear()
End If
End If
Next
DBConnection.Close()

Using parameterized query is causing data type mismatch. Any ideas?

I have a dropdownList with control ID of HourlyCharter.
Then on codebehind, I am trying to query records from the database where hourly is equal to the value of HourlyCharter.
If I use this code:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = " & HourlyCharter.SelectedValue
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
It works.
If I use parameterized query such as this:
StrSQL = "select h.fare, h.tip, h.total from hourlyQRY h "
StrSQL += " Where h.Hourly = #hourly"
' Initialize Database Connection
Dim connStr As String = ConfigurationManager.ConnectionStrings("ALSConnectionString").ConnectionString
Dim conn As New OleDbConnection(connStr)
Dim cmd As New OleDbCommand(StrSQL, conn)
'We use parametized query to prevent sql injection attack
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
I get following error:
Data type mismatch in criteria expression
Hourly is of Number data type and we are using Access 2010 database.
Any ideas how to resolve this?
'open recordset to receive db values
rs = cmd.ExecuteReader()
' This acts like the (Not RecordSource.Eof) in ASP 3.0 to loop and retrieve records.
While rs.Read()
' If rs("city") <> "" Then
Dim tipValue As Decimal = rs("tip")
Dim totValue = rs("total")
' Else
' End If
Dim tp As String = [String].Format("{0:C}", tipValue)
Dim tot As String = [String].Format("{0:C}", totValue)
lblTip.Text = tp
lblTotal.Text = tot
End While
You need to make sure the object you put in the parameter is also a numeric type. SelectedValue is a string.
Dim p1 As New OleDbParameter("#hourly", Decimal.Parse(HourlyCharter.SelectedValue))
That's where the data type mismatch happens - it's expecting a number but it's getting a string.
Instead of
Dim p1 As New OleDbParameter("#hourly", HourlyCharter.SelectedValue)
cmd.Parameters.Add(p1)
You can try
cmd.Parameters.AddWithValue("#hourly", HourlyCharter.SelectedValue)
Try specifying the datat type of the parameter. You can do it after creating it:
p1.OleDbType = OleDb.OleDbType.Numeric
You can also do it on the constructor, but it requires a lot more parameters and I'm not sure you have all those nor I do know what they do.

need quick fix to sql errors

I'm having problems with this block of code, the error is: String or binary data would be truncated
Protected Sub FormView1_ItemInserting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.FormViewInsertEventArgs) Handles FormView1.ItemInserting
Using cnnentry As New SqlConnection("Data Source=NB-1492\sqlipt;Initial Catalog=Bookings;Integrated Security=True;Pooling=False")
Dim entrclientid As String
Dim clid As New TextBox
clid = FormView1.FindControl("txtclientid")
entrclientid = clid.Text
Dim sql As String = "INSERT INTO BOOKING_DETAILS(CLIENT_ID,BOOKING_DATE,REGO,CHECK_IN_DATE,CHECK_OUT_DATE,ROOM_ID) VALUES(#ROOM_ID,#CHECK_OUT_DATE,#CHECK_IN_DATE,#CLIENT_ID,#BOOKING_DATE,#REGO)"
Dim cmdentry As New SqlCommand(sql, cnnentry)
cmdentry.Parameters.AddWithValue("#CLIENT_ID", clid.Text)
Dim curdate As New TextBox
curdate = FormView1.FindControl("txtdate")
cmdentry.Parameters.AddWithValue("#BOOKING_DATE", curdate.Text)
Dim rego As New TextBox
rego = FormView1.FindControl("RegoTextBox")
cmdentry.Parameters.AddWithValue("#REGO", rego.Text)
Dim textin As New TextBox
textin = FormView1.FindControl("textcheckin")
cmdentry.Parameters.AddWithValue("#CHECK_IN_DATE", textin.Text)
Dim textout As New TextBox
textout = FormView1.FindControl("textcheckout")
cmdentry.Parameters.AddWithValue("#CHECK_OUT_DATE", textout.Text)
Dim txtroomid As New TextBox
txtroomid = Session.Item("room_tpe")
cmdentry.Parameters.AddWithValue("#ROOM_ID", roomtype.Text)
cnnentry.Open()
strclid = cmdentry.ExecuteNonQuery()
cnnentry.Close()
End Using
End Sub
can somebody explain why i am getting this error?
the table data types are as follows:
Booking_ID int
Room_ID int
Check_In_Date nvarchar(MAX)
Check_Out_Date nvarchar(MAX)
Booking_Date nvarchar(MAX)
Client_ID nchar(11)
Rego nvarchar(6)
Room_Cost money
Thanks in advance
You are trying to insert data to a field which can not be held by defined datatype.
E.g : VARCHAR(3) can not hold 'TestData'.
In the table BOOKING_DETAILS check column datatypes.

xml response http post - convert request.inputstream to string - asp.net

I'm receiving an xml response and I now want to parse this.
Currently what I have to receive the XML response is:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
How can I go ahead now a process this and pick out the element values?
<subscription>
<reference>abc123</reference>
<status>active</status>
<customer>
<fname>Joe</fname>
<lname>bloggs</lname>
<company>Bloggs inc</company>
<phone>1234567890</phone>
<email>joebloggs#hotmail.com</email>
</customer>
</subscription>
If I have it in string format I can do this using
Dim xmlE As XElement = XElement.Parse(strXML) ' strXML is string version of XML
Dim strRef As String = xmlE.Element("reference")
Do I need to convert the request.inputstream to a strign format or is there another better way?
Thanks
Do I need to convert the request.inputstream to a strign format or is there another better way?
You could directly load it from the request stream, you don't need to convert it to a string:
Request.InputStream.Position = 0
Dim Xmlin = XDocument.Load(Request.InputStream)
Dim reference = Xmlin.Element("subscription").Element("reference").Value
or:
Dim reference = Xmlin.Descendants("reference").First().Value
In the end after much testing I could only get this to work:
Dim textReader = New IO.StreamReader(Request.InputStream)
Request.InputStream.Seek(0, IO.SeekOrigin.Begin)
textReader.DiscardBufferedData()
Dim Xmlin = XDocument.Load(textReader)
Dim strXml As String = Xmlin.ToString
Dim xmlE As XElement = XElement.Parse(strXml)
Dim strRef As String = xmlE.Element("reference")
Dim strStatus As String = xmlE.Element("status")
Dim strFname As String = xmlE.Element("customer").Element("fname").Value()
Dim strLname As String = xmlE.Element("customer").Element("lname").Value()
Dim strCompany As String = xmlE.Element("customer").Element("company").Value()
Dim strPhone As String = xmlE.Element("customer").Element("phone").Value()
Dim strEmail As String = xmlE.Element("customer").Element("email").Value()

Getting row Count only returns value of 1

I am using Sql Server 2005 and Vb Studios 2010 on a .net Framework of 4.0. I am trying to get the exact number of rows from a database and populate a datatable then have a label show the number of rows.
Dim comm2 = db.selectcommand(db.conn, "*", "Tablename", " columnname = '" & Session(sessionvariable) & "' AND columnname = 'Unread '")
Dim sqlda2 As New SqlDataAdapter(comm2)
Dim dt2 As New DataTable
sqlda2.Fill(dt2)
Dim recordcount As Integer = dt2.Rows.Count
messagecountlbl.Text = recordcount
this will always return the value of 1 and I know for a fact that I have multiple values for the data I am trying to pull. I have atleast 50 and the label should be displaying that amount.
I have also tried the Select Count statement and it does the same thing.
Fix I have added this to the post since there is a 24 hr wait to answer question:
I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
Aren't you missing quotes around Unread?
Also... you're susceptible to SQL Injection. Use Parameters instead
Also... if all you are doing is getting the number of rows, your code is overkill
I just noticed.... you Dimmed comm2 but your adapter uses comm
Your updated question was the route that I would have gone. This was why i said your initial code was overkill (in terms of memory usage...). DataAdapters and DataTables for one value is in no way efficient.
You might want to change your updated code to the following...
Again, look up SQL Injection to see why you should never (or at least try not to) build a sql string like that
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = #param"
sql.Parameters.AddWithValue("#param", Session("sessionvariable"))
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult
It looks like you're missing a single quote at the beginning of the word "Unread".
...& "' AND columnname = 'Unread'")
I note that your first line declares a variable called comm2 but you don't use it later - instead you're using simply comm.
With that in mind, the fact that you've omitted the quotes around Unread will still be relevant.
Fix I have added this to the post since there is a 24 hr wait to answer question: I have found a quick and simple fix that I will shorten later in a class file that I have written but this should help alot of people out.
Dim sqlresult As Object
Dim constring As String = "Connection string goes here"
Dim dbcon As SqlConnection = New SqlConnection(constring)
Dim sql As New SqlCommand
dbcon.Open()
sql.Connection = dbcon
sql.CommandText = "SELECT COUNT (*) FROM Tablename WHERE Columnname = 'Unread' AND columnname = '" & Session("sessionvariable") & "'"
sqlresult = sql.ExecuteScalar
messagecountlbl.Text = sqlresult

Resources