Error on ExecuteNonQuery(); - asp.net

I get the following error from ExecuteNonQuery()
"String or binary data would be truncated. The statement has been terminated."
The problem is the variable to be sent is bigger that the one in the DB.
I am using the following code:
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//GridViewRow row = GridView1.SelectedRow;
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
var Username = (Label)row.FindControl("Label3");
var Password = (Label)row.FindControl("Label4");
var Email = (Label)row.FindControl("Label5");
// var ID_Inscricao = ((Label)row.FindControl("Label1")).Text;
var ID_Inscricao = ((Label)row.FindControl("Label1")).Text;
SqlConnection sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["FormacaoConnectionString"].ToString());
SqlCommand sqlComm = new SqlCommand();
sqlComm = sqlConn.CreateCommand();
sqlComm.Parameters.Add("#Username", SqlDbType.Text);
sqlComm.Parameters.Add("#Password", SqlDbType.Text);
sqlComm.Parameters.Add("#Email", SqlDbType.Text);
sqlComm.Parameters.Add("#ID_Inscricao", SqlDbType.Int);
sqlComm.Parameters["#Username"].Value = Convert.ToString(Username);
sqlComm.Parameters["#Password"].Value = Convert.ToString(Password);
sqlComm.Parameters["#Email"].Value = Convert.ToString(Email);
sqlComm.Parameters["#ID_Inscricao"].Value = Convert.ToInt32(ID_Inscricao);
string sql = "INSERT INTO Utilizadores (Username, Password, Email, ID_Inscricao) VALUES (#Username, #Password, #Email, #ID_Inscricao)";
sqlComm.CommandText = sql;
sqlConn.Open();
sqlComm.ExecuteNonQuery();
sqlConn.Close();
}

This happens when you try to insert something into a column that is too long for that column.
For example, when you have a column VARCHAR(10) and you try to insert the value "ABCDEFGHIJKLMNOP". This would lead to the data being truncated and that generates an error.
I can't tell which column it is in your case but it has to be one of Username, Password or Email.

The issue is the data type in the database you are trying to populate is smaller than one of the values you are passing. You need to check each of your parameters #Username, #Password and #Email and see which one is larger than the database data type. Then you can increase the size of the data type in the database if required, or trim the parameter values before sending.

Dim qry As String
qry = "inserg into Table1 values('" & TextBox1.Text & "'+'" & TextBox2.Text & "'+'" & DropDownList1.Text & "'+'" & DropDownList2.Text & "'+'" & TextBox4.Text & "'+'" & TextBox5.Text & "'+'" & RadioButtonList1.Text & "'+'" & RadioButton1.Text & "'+'" & RadioButtonList2.Text & "'+'" & CheckBoxList1.Text & "'+'" & TextBox6.Text & "'+'" & TextBox7.Text & "'+'" & TextBox8.Text & "'+'" & TextBox9.Text & "'+'" & TextBox10.Text & "'+'" & RadioButtonList3.Text & "'"
Dim cn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Documents and Settings\MCALab\My Documents\net.mdb")
Dim cmd As New OleDbCommand(qry, cn)
cn.Open()
**cmd.ExecuteNonQuery()**this line have error please any one know mean debug it.
cn.Close()

Related

How to get data from SQL Server database and display it in dropdownlist + asp.net vb

I have a dropdownlist which contains Yes and No. By default the value is Yes. I want to extract the value from a SQL Server database but at the same time it also can be edited either want to remain yes or change to No.
Currently my source code only show one value.
Example: first time I choose Yes and it will go to database, when search again, the value show Yes. But I cannot choose No. I need to change value to No.
Here is my source code:
strsql = "Select IN_USE FROM FixedAssetMaster_old WHERE ASSET_NUMBER=" & AssetTxt.Text & " AND LOC_DEPT=" & DeptTxt.Text & " AND UNIT_NO=" & UnitNoTxt.Text & " And (DATEPART(MM, UPDATE_DATE) = " & nowMonth & ") And (DATEPART(yyyy, UPDATE_DATE) =" & nowYear & ") ;"
da = New SqlDataAdapter(strsql, Conn)
Dim ds As New DataSet()
da.Fill(ds)
da.Dispose()
DDLInUse.DataSource = ds
DDLInUse.DataTextField = "IN_USE"
DDLInUse.DataValueField = "IN_USE"
DDLInUse.DataBind()
'DDLInUse.Items.Insert(0, "")
ds.Dispose()
Try this
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(str);
string com = "Select * from UserDetail";
SqlDataAdapter adpt = new SqlDataAdapter(com, con);
DataTable dt = new DataTable();
adpt.Fill(dt);
DropDownList1.DataSource = dt;
DropDownList1.DataBind();
DropDownList1.DataTextField = "Name";
DropDownList1.DataValueField = "ID";
DropDownList1.DataBind();
}

search query from 2 dates and 2 time

I have 4 Datetimepicker. the 2 datetimepicker is on dateformat(datefrom,dateto) and the other 2 datetimepicker is on Timeformat(timefrom,timeto).
I want to search a table that display only in datagridview that will display only start on Date from and time from to date to and time to... But my code doenst work.
here's my code:
Dim fromto As String = String.Empty
fromto &= "Select * from setplan where endplan >='" & dtimefrom.Text & "'and endplan >='" & dtimeto.Text & "' and [Dateinput] >='" & ddatefrom.Text & "' and [dateinput] <= '" & ddateto.Text & "'"
Dim connection As String = ("provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Administrator\Documents\planning.accdb;Persist Security Info=False;")
Using conn As New OleDb.OleDbConnection(connection)
Using cmd As New OleDb.OleDbCommand(fromto)
With cmd
.Connection = conn
.CommandType = CommandType.Text
.CommandText = fromto
End With
Try
conn.Open()
cmd.ExecuteNonQuery()
Dim da As New OleDb.OleDbDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
If ds.Tables.Count > 0 Then
DataGridView1.DataSource = ds.Tables(0)
End If
conn.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Using
End Using
End Sub
You need formatted string expressions for your date/time values:
fromto &= "Select * from setplan where endplan >= #" & ddateto.Value.ToString("yyyy'/'MM'/'dd") & " " & dtimeto.Value.ToString("HH':'mm") & "# and [dateinput] >= #" & ddatefrom.Value.ToString("yyyy'/'MM'/'dd") & " " & dtimefrom.Value.ToString("HH':'mm") & "#"

oleDbexception was unhandled by user code

I cannot see the added data in the data table when debugging starts it doesn't have any error but when I click button1 it shows me errors (unhandled by user code) unclosed quotation mark after the character string ')'
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim con As OleDbConnection
Dim strInsert As String
Dim cmdInsert As OleDbCommand
Dim vt As Byte, vm As Byte
Dim sze As Byte
con = New OleDbConnection("Integrated Security=SSPI;Packet Size=4096;Data Source=.;Tag with column collation when possible=False;Initial Catalog=borjara;Use Procedure for Prepare=1;Auto Translate=True;Persist Security Info=False;Provider=SQLOLEDB.1;Workstation ID=ABDI;Use Encryption for Data=False")
If RadioButton4.Checked = True Then vt = 0
If RadioButton5.Checked = True Then vt = 1
If RadioButton6.Checked = True Then vm = 0
If RadioButton7.Checked = True Then vm = 1
If RadioButton8.Checked = True Then vm = 2
If RadioButton9.Checked = True Then szs = 1
If RadioButton10.Checked = True Then szs = 0
con.Open()
strInsert = "insert Into t1(jens) Values (" & DropDownList1.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()//error is here
con.Close()
con.Open()
strInsert = "insert Into t1(bazsho) Values (" & DropDownList2.SelectedItem.Text & "')"
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
con.Open()
strInsert = "insert Into t1(name and lastname,email,number,address,lenght,wideth,turi,glasstype,glass) Values (" & n & ",'" & TextBox1.Text(+" / " + TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "','" & TextBox5.Text & "','" & TextBox6.Text & "'," & vt & "," & vm & "," & szs & "')")
cmdInsert = New OleDbCommand(strInsert, con)
cmdInsert.ExecuteNonQuery()
con.Close()
TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""
TextBox6.Text = ""
End Sub
End Class
It looks like there is no opening quote in the values of the first two Inserts.

Add User to Database not working

I'm really new to ASP.net and I am currently trying to create a registration page on a site. I was successful in adding a user to the database but I decided to add another feature into the code to check what userID's were available. For example, if a user deleted their account their userID would become available for use again. I'm trying to find the min value and the max value and add or subtract 1 depending on whether it is min or max. I can run the code I have written for this with no errors but the user is not added to the database. Can anyone help me figure out what I'm missing from my code to do this?
EDIT >>>>>
Code adds a user to database but it adds the new user at -1 instead. I don't seem to be able to see where the issue is.
If (aDataReader2.Read() = False) Then
aConnection1 = New OleDbConnection(aConnectionString)
aConnection1.Open()
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection1)
aCommand.ExecuteNonQuery()
aConnection1.Close()
ElseIf (min = 1) Then
aConnection2 = New OleDbConnection(aConnectionString)
aConnection2.Open()
aCommand = New OleDbCommand(aQuery3, aConnection2)
aDataReader2 = aCommand.ExecuteReader()
userID = max + 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection2)
aCommand.ExecuteNonQuery()
aConnection2.Close()
Else
aConnection3 = New OleDbConnection(aConnectionString)
aConnection3.Open()
aCommand = New OleDbCommand(aQuery2, aConnection3)
aDataReader2 = aCommand.ExecuteReader
userID = min - 1
aQuery = "Insert Into UserDetails "
aQuery = aQuery & "Values ('" & userID & "','" & userFName & "','" & userLName & "','" & userEmail & "','" & userUsername & "','" & userPassword & "')"
aCommand = New OleDbCommand(aQuery, aConnection3)
aCommand.ExecuteNonQuery()
aConnection3.Close()
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
Here's the code I used to get the max and min values from the database. I'm getting a value of 0 for both of them - when min should be 1 and max should be 5
Dim minID As Integer
Dim maxID As Integer
aQuery2 = "Select Min(UserID) AS '" & [minID] & "' From UserDetails"
aQuery3 = "Select Max(UserID) AS ' " & [maxID] & "' From UserDetails"
It's hard to say what
t the problem is exactly, since we see only a part of it. Where do min and max come from?
I cannot give you a solution, however, I suggest you to structure your code better. You have a lot (!) of redundant code. This makes the code difficult to read, to understand, to change and to test.
Put the user data into a class. This makes it easier to handle than a lot of individual variables.
Public Class User
Public Property ID As Integer
Public Property FirstName As String
Public Property LastName As String
Public Property EMail As String
Public Property Username As String
Public Property Password As String
End Class
Extract redundant code into subroutines
Private Sub CreateUser(ByVal u As User)
Const InsertQuery As String = _
"INSERT INTO UserDetails VALUES ({0},'{1}','{2}','{3}','{4}','{5}')"
Dim query As String = String.Format(InsertQuery, u.ID, u.FirstName, u.LastName, _
u.Email, u.Username, u.Password)
Using conn As New OleDbConnection(aConnectionString)
conn.Open()
Dim cmd As New OleDbCommand(query, conn)
cmd.ExecuteNonQuery()
End Using
End Sub
The code then becomes something like this
If Not aDataReader2.Read() Then
CreateUser(user)
ElseIf min = 1 Then
...
user.userID = max + 1
CreateUser(user)
Else
...
user.userID = min - 1
CreateUser(user)
lblResults.Text = "User Account successfully created"
btnCreateUser.Enabled = False
End If
This looks much nicer now.
(My code is not tested, it's just to give you an idea.)
UPDATE
You cannot read the min and max values like this. Try something like this
Dim min, max As Integer
Using conn As New OleDbConnection(aConnectionString)
Dim cmd As OleDbCommand = _
New OleDbCommand("SELECT MIN(UserID), MAX(UserID) FROM UserDetails", conn)
conn.Open()
Using reader As OleDbDataReader = cmd.ExecuteReader()
reader.Read()
If reader.IsDBNull(0) Then
' The table is empty
min = 1
max = 1
Else
min = reader.GetInt32(0)
max = reader.GetInt32(1)
End If
End Using
End Using

Insert into Access DB (loop)

I have this code and its coming up with an INSERT INTO statement error...
Its probably something but I have been at it for a while... please help.
'Add items to db'
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
For intCounter = 0 To objDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data source=" & myPath2 & ";"
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.CommandText = "INSERT INTO order(order_date, coupon_id, customer_id, quantity) values('" & System.DateTime.Now & "','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) & "','" & Int32.Parse(objDR("quantity")) &"')"
myCommand2.Connection = con2
con2.Open()
myCommand2.ExecuteReader()
con2.Close()
test.Text += "Order ID: " & objDR("ID") & "Order Date: " & System.DateTime.Now & ", Cust ID: " & custID & ", Quantity: " & objDR("quantity") &" "
Next
End Function
I think you are getting an error by not enclosing the Date inside Pound signs. You have to do this in Jet (Access) when using variables not parameters.
VALUES('#" & DateTime.Now.Date & "#',...
I also took the liberty of refactoring this code for you since you are creating a new connection for each record which is bad news. Use a Try Catch Finally block and move all that stuff outside the For Loop (please see below)
Function recordOrder()
objDT = Session("Cart")
Dim intCounter As Integer
Dim con2 As New System.Data.OleDb.OleDbConnection
Dim myPath2 As String
myPath2 = Server.MapPath("faraxday.mdb")
con2.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" <-- etc
Dim myCommand2 As New System.Data.OleDb.OleDbCommand
myCommand2.Connection = con2
con2.Open()
Try
For intCounter = 0 To obDT.Rows.Count - 1
objDR = objDT.Rows(intCounter)
myCommand2.CommandText = "INSERT INTO order(order_date,coupon_id,customer_id,quantity)" _
& "VALUES ('#" & System.DateTime.Now.Date & "#','" & Int32.Parse(objDR("ID")) & "','" & Int32.Parse(custID) _
& "','" & Int32.Parse(objDR("quantity")) & "')"
myCommand2.ExecuteReader()
Next
Catch ex As Exception
'handle errors here
Finally
If con2.State = ConnectionState.Open Then
con2.Close()
End If
End Try
End Function
Remember to mark as answered if this helps.
I've sorted it out by removing the single quotes. Thanks everybody to contributed to this.

Resources