need quick fix to sql errors - asp.net

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.

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()

Check if Record Exists IN DB Using ASP VB

I am trying to check whether an email exists in my sql database from an an asp code behind
Basically a user will fill in a form and submit, I need to check wther that email exists first before inserting
Protected Sub btnSignup_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSignup.Click
Response.Cookies("survey")("fullname") = TextBoxFullName.Text
Response.Cookies("survey")("surname") = TextBoxSurname.Text
Response.Cookies("survey")("lastVisit") = DateTime.Now.ToString()
Response.Cookies("survey")("contactnumber") = TextBoxPhone.Text
Response.Cookies("survey")("email") = TextBoxEmail.Text
Response.Cookies("survey").Expires = DateTime.Now.AddDays(365)
'InsertCommand="INSERT INTO [Comp_20140409_Broadband] ([SignupName], [SignupGender], [SignupIDNo], [SignupEmailAddress], [CurrentProvider], [CurrentSpeed], [CurrentUsage]) VALUES (#SignupName, #SignupGender, #SignupIDNo, #SignupEmailAddress, #CurrentProvider, #CurrentSpeed, #CurrentUsage)"
If Not Page.IsValid Then Exit Sub
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim updateSql3 As String = "Select [PersonId] FROM [Users] WHERE [Email] = #Email"
Dim PersonId As Integer
Using myConnection As New SqlConnection(connectionString)
myConnection.Open()
Dim myCommand As New SqlCommand(updateSql3, myConnection)
myCommand.Parameters.AddWithValue("#Email", TextBoxEmail.Text)
PersonId = myCommand.ExecuteScalar()
myConnection.Close()
End Using
Dim updateSql2 As String = " INSERT INTO [Survey_Legal] ([LegalInsurance],[ThirdParty], [LegalIssues], [RequestLegal], [PersonId], [Category_Type]) VALUES (#LegalInsurance, #ThirdParty, #LegalIssues, #RequestLegal, #PersonId, #Type )"
Using myConnection2 As New SqlConnection(connectionString)
myConnection2.Open()
Dim myCommand2 As New SqlCommand(updateSql2, myConnection2)
myCommand2.Parameters.AddWithValue("#LegalInsurance", DDLLegal1.SelectedValue)
myCommand2.Parameters.AddWithValue("#ThirdParty", DDLLegal2.SelectedValue)
myCommand2.Parameters.AddWithValue("#LegalIssues", DDLLegal3.SelectedValue)
myCommand2.Parameters.AddWithValue("#RequestLegal", DDLLegal4.SelectedValue)
myCommand2.Parameters.AddWithValue("#PersonId", PersonId)
myCommand2.Parameters.AddWithValue("#Type", "Legal-Insurance")
myCommand2.ExecuteNonQuery()
myConnection2.Close()
End Using
This is how I do this. I check for a duplicate email address in my stored procedure with an output parameter.
CREATE Procedure sp_AddSubscriber
#Name as nvarchar(50),
#Email as nvarchar(50),
#AddSubscriber bit OUTPUT
AS
IF (SELECT COUNT(Email)
FROM TSubscribers
WHERE Email = #Email) = 0
BEGIN
INSERT TSubscribers (Name, Email)
VALUES (#Name, #Email)
SET #AddSubscriber = False
END
ELSE
SET #AddSubscriber = True
GO

unhandled exception error won't allow me to insert data

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)

Get Data from One Table and Insert to Another Via Form Submission

How do I get a UserID from one database table (Users) to be inserted into another table (Ticket)? Both columns in each table has the same datatype (int). Please take a look:
Users
UserID
UserName
Password
FirstName
LastName
Email
Updated
Deleted
Ticket
TicketID
DateCreated
UserIDNum FK
FullName
Email
Subject
Message
Deleted
These are all of the codes involved:
Partial Public Class mysupport
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Page.IsPostBack Then
MaintainScrollPositionOnPostBack = True
SetFocus(helpTopicDDL)
Else
SetFocus(fullNameTXTBOX)
End If
Dim sConnection As New SqlConnection(ConfigurationManager.ConnectionStrings("TrackTicketsConnectionString2").ConnectionString)
sConnection.Open()
If Session("Ticket") Is Nothing Then
Response.Redirect("SignIn.aspx")
Else
Dim cmdS As String = "Select * from Users Where Deleted='N' AND Username=#Username"
Dim cmdCheckEmail As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#Username", Data.SqlDbType.VarChar)
cmdCheckEmail.Parameters.Add("#Username", SqlDbType.VarChar)
cmdCheckEmail.Parameters.Item("#Username").Value = Session("Ticket")
Dim obj As Object = cmdCheckEmail.ExecuteScalar()
If obj IsNot Nothing Then
mailLBL.Text = Convert.ToString(obj)
End If
End If
sConnection.Close()
End Sub
Protected Sub submitBTN_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitBTN.Click
Dim sdConnection As String = ConfigurationManager.AppSettings("TrackTicketsConnectionString2")
Dim iRowCount As Integer
Dim cmdInsertTicket As New Data.SqlClient.SqlCommand
Dim conticket As New Data.SqlClient.SqlConnection
conticket.ConnectionString = sdConnection
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "Insert Into Ticket " _
& "( DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values( #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
'Dim appUserName As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.NVarChar)
'cmdInsertTicket.Parameters.Add(appUserName)
'cmdInsertTicket.Parameters.Item("#UserName").Value = User.Identity.Name
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
Dim appFullName As New Data.SqlClient.SqlParameter("#FullName", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appFullName)
cmdInsertTicket.Parameters.Item("#FullName").Value = fullNameTXTBOX.Text
Dim appEmail As New Data.SqlClient.SqlParameter("#Email", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appEmail)
cmdInsertTicket.Parameters.Item("#Email").Value = emailAddTXTBOX.Text
Dim appTicketType As New Data.SqlClient.SqlParameter("#TicketType", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appTicketType)
cmdInsertTicket.Parameters.Item("#TicketType").Value = helpTopicDDL.SelectedValue
Dim appSubject As New Data.SqlClient.SqlParameter("#Subject", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appSubject)
cmdInsertTicket.Parameters.Item("#Subject").Value = subjectTXTBOX.Text
Dim appMessage As New Data.SqlClient.SqlParameter("#Message", Data.SqlDbType.VarChar)
cmdInsertTicket.Parameters.Add(appMessage)
cmdInsertTicket.Parameters.Item("#Message").Value = messageTXTBOX.Text
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
conticket.Open()
Try
iRowCount = cmdInsertTicket.ExecuteScalar()
statusLBL.Text = "Ticket has been submitted successfully."
Catch
statusLBL.Text = "Ticket has not been submitted. Please try again."
End Try
conticket.Close()
End Sub
What I really wanted is for a person's UserID to be stored in Ticket table after he has logged in to fill out a form and submitted it. I'm at a loss in how to pull the data from Users table to insert into Ticket table. Any help is much appreciated as I'm still learning.
EDIT:
Inserting the UserID into the Tickets table when adding a record first requires that you have access to the UserID value. You then need to pass this value in your INSERT statement.
Looks like we first need to retrieve the UserId. Since you are using FormsAuthentication we can retrieve the UserName from the User.Identity.Name object and use that as the value in our first query to retrieve the UserId.
Dim cmdS As String = "Select [UserID] from Users Where Deleted='N' AND UserName=#UserName"
Dim cmdGetUserId As New SqlCommand(cmdS, sConnection)
Dim cmd As New Data.SqlClient.SqlParameter("#UserName", Data.SqlDbType.VarChar)
cmdGetUserId.Parameters.Add("#UserName", SqlDbType.VarChar)
cmdGetUserId.Parameters.Item("#UserName").Value = User.Identity.Name
Dim obj As Object = cmdGetUserId.ExecuteScalar
Dim myUserId As Integer = Integer.Parse(obj)
Now that we have the UserId value for our current user we can modify our INSERT statement and parameters.
cmdInsertTicket.Connection = conticket
cmdInsertTicket.CommandText = "INSERT INTO Ticket " _
& "(UserID, DateCreated, FullName, Email, TicketType, Subject, Message, Deleted)" _
& "Values(#UserID, #DateCreated, #FullName, #Email, #TicketType, #Subject, #Message, #Deleted)"
Dim appUserId As New Data.SqlClient.SqlParameter("#UserID", Data.SqlDbType.Int)
cmdInsertTicket.Parameters.Add(appUserId)
cmdInsertTicket.Parameters.Item("#UserID").Value = myUserId
Dim appDateCreated As New Data.SqlClient.SqlParameter("#DateCreated", Data.SqlDbType.DateTime)
cmdInsertTicket.Parameters.Add(appDateCreated)
cmdInsertTicket.Parameters.Item("#DateCreated").Value = Now()
...
Dim appDeleted As New Data.SqlClient.SqlParameter("#Deleted", Data.SqlDbType.Char)
cmdInsertTicket.Parameters.Add(appDeleted)
cmdInsertTicket.Parameters.Item("#Deleted").Value = "N"
You can access authentication information through the User.Identity object once the user has been authenticated. Might also want to think about implementing a custom IIdentity class to store the UserID if you will need access to it often. Here's a good MSDN article about Custom Authentication: http://msdn.microsoft.com/en-us/library/ms172766(v=vs.80).aspx
UPDATE:
In regards to the comment below, you are retrieving the UserID because the SqlCommand is being executed with the ExecuteScalar method which returns the value of the first column of the first row. I would recommend taking a closer look at the SqlCommand object: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx and this ADO.NET primer on MSDN: http://msdn.microsoft.com/en-us/library/e80y5yhx(v=vs.80).aspx

How to populate a text box with value from DB

I am new to asp.net and here I am trying to populate a single text box with a value from database.
I have created this code but not working:
Try
Dim MyCon As New SqlConnection("server = servername; uid = sa; pwd =abc; database = master")
Dim MyCommand As New SqlCommand("Select empFirstName from Employees where empid=2")
MyCon.Open()
Dim MyReader = MyCommand.ExecuteReader()
While MyReader.Read()
Dim sqlda = New SqlDataAdapter()
Dim dt As New Data.DataTable()
Dim ds As New Data.DataSet
sqlda.Fill(ds)
TextBox1.Text = ds.Tables(0).ToString
MyCon.Close()
End While
Please correct the code and tell me where I am wrong.
Kindly suggest me a link if any to read more on this topic for beginners with example.
Try this sample, it will work for you http://geekswithblogs.net/dotNETvinz/archive/2008/09/12/bind-textbox-and-label-control-with-data-from-database.aspx
ds.Tables(0)
will return a DataTable
If you want to get the tablename, write this instead:
ds.Tables(0).TableName
If you want to get value returned, write this kind of code:
ds.Tables(0).Rows(0).Item("empFirstName")
This will store only the 1st row from the database
TextBox1.Text = ds.Tables(0).Rows(0)(0).ToString();
Row(0)(0) indicates to get the 1st row from the 1st column
If the query is returning more than 1 rows then u need to iterate the data table and store it in a List(Of String) instead of an array as you don't know the number of rows returned from the query
Dim EmpFirstName As New List(Of String)
Dim myRow As DataRow
Dim myColumn As DataColumn
For Each myRow in dt.Rows
EmpFirstName.Add(myRow(dt.Columns(0)))
Next

Resources