Referring to my last question: "The connection was not closed. The connection's current state is open". I am trying to do a registration form using vb.net with ASP.NET. After having solve an issue concerning 'close connection'. I am having problem to insert data to my database. When I try to validate the data it gives me an error message:
Must declare the scalar variable "#User_Name"
Can someone help me to debug this? Thanks
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Partial Class Register2
Inherits System.Web.UI.Page
'declaring connection string and command
'here we are extracting connection string from web.config file
Private con As New SqlConnection(ConfigurationManager.ConnectionStrings("MauriAuctions").ToString())
Private cmd As New SqlCommand()
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Try
cmd.Connection = con
'assigning connection to command
cmd.CommandType = CommandType.Text
'representing type of command
'cmd.CommandText = "INSERT INTO UserDetails (User_Name,Fname,Lname,Email,Password,Gender,Dob,Mobile,Address) values
' (#User_Name,#Fname,#Lname,#Email,#Password,#Gender,#Dob,#Mobile,#Address)";
cmd.CommandText = "INSERT INTO tbl_user (User_Name, Fname, Lname, Email, Pwd, Street, Town, City, Tel) values(#User_Name,#Fname,#Lname,#Email,#Pwd,#Street,#Town,#City,#Tel)"
'adding parameters with value
cmd.Parameters.AddWithValue("#User_Name", txtUser_Name.Text.ToString())
cmd.Parameters.AddWithValue("#Fname", txtFirstName.Text.ToString())
cmd.Parameters.AddWithValue("#Lname", txtLastName.Text.ToString())
cmd.Parameters.AddWithValue("#Email", txtEmail.Text.ToString())
cmd.Parameters.AddWithValue("#Pwd", txtPassword.Text.ToString())
cmd.Parameters.AddWithValue("#Street", txtStreet.Text.ToString())
cmd.Parameters.AddWithValue("#Town", txtTown.Text.ToString())
cmd.Parameters.AddWithValue("#City", txtCity.Text.ToString())
cmd.Parameters.AddWithValue("#Tel", txtTel.Text.ToString())
cmd.Parameters.Clear()
con.Open()
'opening connection
cmd.ExecuteNonQuery()
'executing query
con.Close()
'closing connection
lblMsg.Text = "Registered Successfully.."
Catch ex As Exception
lblMsg.Text = ex.Message.ToString()
Finally
con.Close()
'closing connection
End Try
End Sub
Protected Sub btnClear_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClear.Click
'refreshing/reloading page to clear all the controls
Page.Response.Redirect(Page.Request.Url.ToString(), True)
End Sub
End Class
You're clearing parameters after adding them. Try putting cmd.Parameters.Clear() before first .AddWithValue, not after the last one.
Related
I'm having a problem when I'm reading data from a SQL Server database. The main thing is that I want to read the data from the database and display the data in a Label control. But the concern is that it can't read data to it. I will show you the code snippet and any comments/suggestions are gladly considered.
Option Explicit On
Imports System.Data
Imports System.Data.OleDb
Partial Class ViewDetail
Inherits System.Web.UI.Page
Dim con As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim InstructorID As Integer
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
InstructorID = Request.QueryString("Instructor_ID")
Integer.TryParse(lblID.Text, InstructorID)
con = New OleDbConnection("Provider=SQLNCLI11;Data Source=ARIES-PC\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=SchoolDB")
con.Open()
cmd = New OleDbCommand("SelectData", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#id", InstructorID)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read
lblID.Text = dr("Instructor_ID").ToString
lblFirstname.Text = dr("FirstName").ToString
lblLastname.Text = dr("LastName").ToString
lblAddress.Text = dr("Address").ToString
lblContact.Text = dr("Contact_Number").ToString
End While
End If
dr.Close()
cmd.Dispose()
con.Close()
End Sub
End Class
This line seems to be totally wrong
Integer.TryParse(lblID.Text, InstructorID)
This lines takes the current value in the lblID.Text at the Page_Load event and tries to set the value of InstructorID. But your code seems to want this value from the QueryString passed that contains the real value.
If you are certain the the QueryString contains a valid integer then remove that line and add
InstructorID = Convert.ToInt32(Request.QueryString("Instructor_ID"))
i want to change textbox information but when i try to do that it's don't work
this is my asp.net vb code
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.SqlClient.SqlDataReader
Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30"
Dim queryString As String = "Update TEST Set chaine1= '" & TextBox1.Text & "' "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
command.ExecuteNonQuery()
connection.Close()
End Sub
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim connectionString As String = "Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\napster\Documents\ZE.mdf;Integrated Security=True;Connect Timeout=30"
Dim queryString As String = "SELECT * from TEST "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
TextBox1.Text = dataReader.GetSqlString(3)
End While
TextBox1.
End Sub
End Class
You should always consider how the ASP.NET model works.
In ASP.NET, when you click a button that executes a server side code (the event) you get always a call to the Page.Load event before the call to your event handler code.
In your Page.Load you execute again the code to load the TextBox from the database, but this code destroys the content of the textbox that has been typed by you. The textbox is set to the original value extracted by the database, so, when the code in the button event handler is executed it writes the same value to the database.
To resolve this situation you need to add this to the Page_Load event
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
if Not IsPostBack Then
Dim connectionString As String = "......"
Dim queryString As String = "SELECT * from TEST "
Dim connection As New SqlConnection(connectionString)
Dim command As New SqlCommand(queryString, connection)
connection.Open()
Dim dataReader As SqlDataReader = command.ExecuteReader()
While dataReader.Read()
TextBox1.Text = dataReader.GetSqlString(3)
End While
End If
End Sub
Said that, please take notice, your code in the button click event is very dangerous because you concatenate whatever is typed by the user to a string that is then passed as a sql command to the database. This is the pattern used by the Sql Injection attacks that could destroy your database or stole valuable information from you tables
I'm writing a simple update-password page (studying purposes). The page consist of two text-box controls that will allow the user to enter their new password, followed by confirming their password by entering it into the second text-box control and finally clicking the submit bottom to update their password in the table stored in a database. My problem is that I receive the following error upon button-click: Format of the initialization string does not conform to specification starting at index 0 Error.
This is the code in behind he button:
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox2.Text = TextBox3.Text Then
Dim myConnectionString As String
myConnectionString = "myDbIIConnectionString1"
Dim myConnection As New SqlConnection(myConnectionString)
myConnection.Open()
Dim mySQLQuery As String
mySQLQuery = "UPDATE myTb SET password VALUES (#password)"
Dim myCommand As New SqlCommand(mySQLQuery, myConnection)
myCommand.Parameters.AddWithValue("#password", TextBox3.Text)
myCommand.Connection = myConnection
myCommand.ExecuteNonQuery()
myCommand = Nothing
myConnection.Close()
myConnection = Nothing
Label2.Text = "Your Password has been changed"
Else
Label2.Text = "Retype your Password"
End If
Response.Redirect("login.aspx")
End Sub
Could someone assist me as to what I'm missing here? Thank You
There is problem in your update query . Correct it as :
mySQLQuery = "UPDATE myTb SET password=#password"
I figured it out; I should have been using configurationmanager.connectionstrings["the name goes here"]. to access my connection string.
I am currently doing a project on web service for wine. I have the wine table with wineName and wineType. Also I have the search function implemented in the webservice coding as well as a separate webform to call the function of the search function
I have the following code for performing search in the search service:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Dim con As New SqlConnection(connectionString)
Dim selectSql As String = "SELECT * From Wine WHERE WineType='" & searchName + "'"
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(selectSql, con)
Dim ds As New Data.DataSet
con.Open()
selectAdapter.Fill(ds, "Wine")
con.Close()
Return ds
End Function
As for the webform, it's just a simple page with textbox labeled as searchName, a button and a gridView1 tied to ObjectDataSource.
This is the coding i have for webform:
Partial Class Search
Inherits System.Web.UI.Page
Dim searching As searchwine.Service = New searchwine.Service
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
If searchName.Text = "" Then
lblDisplayError.Text = "Can't search empty field!"
Else
Dim ds As DataSet = searching.Search(searchName.Text)
GridView1.DataSource = ds.Tables(0)
GridView1.DataBind()
GridView1.Visible = True
lblDisplayError.Visible = False
End If
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
lblDisplayError.Text = ""
GridView1.Visible = False
End Sub
End Class
Everything seems fine, but i have the following error when i want to do a search:
System.NullReferenceException: Object reference not set to an instance of an object. at Service.Search(String searchName)
Can anyone help me out please?
I've looked through your code a couple times and I can't see what's causing the NullReferenceException. My best guess is that it couldn't find a connection string name "ConnectionString" in your web.config file, but even that doesn't quite seem to fit.
I can suggest some improvements to your search code. Hopefully you'll at least get a better error message out of this:
<WebMethod()> _
Public Function Search(ByVal searchName As String) As System.Data.DataSet
Dim ds As New Data.DataSet()
Dim connectionString As String = ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString
Using con As New SqlConnection(connectionString), _
cmd As New SqlCommand("SELECT * From Wine WHERE WineType= #SearchName", con)
'I had to guess at the exact length and type of the field here
cmd.Parameters.Add("#SearchName", SqlDbType.VarChar, 50).Value = searchName
Dim selectAdapter As New Data.SqlClient.SqlDataAdapter(cmd, con)
selectAdapter.Fill(ds, "Wine")
End Using
Return ds
End Function
But in the end I expect you'll need to step through the method and see exactly which line above throws the exception.
Looks like you are missing a New
Dim ds As DataSet = searching.Search(searchName.Text)
Should be...
Dim ds As **New** DataSet = searching.Search(searchName.Text)
anyone can help me to connect to SQL server through vb.net using asp.net webform.. I have the database name Users and i want to use the database for the login page.. please help me..
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim ConnectionString As String
ConnectionString = ConfigurationSettings.AppSettings("ConnectionString")
Dim con As New SqlConnection(ConnectionString)
Dim cmd As New SqlCommand("Select UserId, Pwd from Users", con)
con.Open()
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader()
While myreader.Read()
If TxtUserId.Text = myreader("UserId").ToString().Trim()
AndAlso TxtPwd.Text = myreader("Pwd").ToString().Trim() Then
Session("UserId") = TxtUserId.Text
Response.Redirect("UserMyProfile.aspx")
Else
lblMsg.Visible = True
lblMsg.Text = "Inavalid UserId/Password"
End If
End While
con.Close()
End Sub
There's no shortage of tutorials on the web for this, but a good starting point is here.
EDIT: Based on your comments above, it sounds like you're not importing the Namespace you need for the ADO.NET data objects. Try adding this to the class file:
Imports System.Data.SqlClient