Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
Dim Uname As String
Dim pwd As String
Dim pName As String
Dim reader As SqlDataReader
Uname = Login1.UserName
pwd = Login1.Password
pName = ""
Dim strConn As String
strConn = WebConfigurationManager.ConnectionStrings("ConnectionASPX").ConnectionString
Dim Conn As New SqlConnection(strConn)
Conn.Open()
Dim sqlUserName As String
sqlUserName = "SELECT UserName,Password FROM Customer"
sqlUserName &= " WHERE (UserName = #Uname"
sqlUserName &= " AND Password = #Pwd)"
Dim com As New SqlCommand(sqlUserName, Conn)
com.Parameters.AddWithValue("#Uname", Uname)
com.Parameters.AddWithValue("#Pwd", pwd)
reader = com.ExecuteReader()
If (reader.Read()) Then
Me.Response.Redirect("Faq.aspx")
Else
MsgBox("Invalid UserName-password")
End If
reader.Close()
Conn.Close()
'If CurrentName <> "" Then
' Session("UserAuthentication") = Uname
' Response.Redirect("Faq.aspx")
'Else
' Session("UserAuthentication") = ""
'End If
End Sub
the code kis working without any errors . It is not redirecting to another page.
Put a breakpoint (press F9) on the line If (reader.Read()) Then and then press F5 to run the app in debug mode and step through that line to see if it is skipping your Response.Redirect call. If it is, you will have to figure out why the Read() method is returning false.
Related
I trying to figure out why my code in inserting two records into the database when it executes? the CreateEnrollment Sub executes fine, however the results insert 2 sometimes 3 records ranging from 1-10 seconds apart, depending on remote server load. I first thought it might be the IsPostBack problem but adding the If Not Page.IsPostBack Then did not resolve.
Dim FailedMessage As String = "This COPDI (On-Line) user failed: "
Dim PassedMessage As String = "This COPDI (On-Line) user passes: "
Dim ClassName As String = "COPDI (FAILED)"
Dim SendMailAddress As String = "myEmailAddress.com"
Dim SubsiteConnString As String = "Subsite_appSettings"
Dim MainsiteConnString As String = "SubsiteConn"
Dim RecordsReturned As Integer = 0
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim UserName As String = User.Identity.Name()
Dim userID As Integer = GetUID(UserName)
Dim ClassDate As Date = DateTime.Now.AddHours(3).ToShortDateString
Dim ClassTime As String = DateTime.Now.AddHours(3). ToShortTimeString
If Not Page.IsPostBack Then
If Request.QueryString("code") = 1111 Then
RecordsReturned = RecordExist(UserName)
CreateEnrollment(UserName, ClassDate, ClassTime, ClassName, userID)
UpdateLastActivityDate(UserName)
If RecordsReturned < 3 Then
Response.Redirect("~/transcript.aspx" & "?code=" & RecordsReturned)
Else
Response.Redirect("~/transcript.aspx" & "?code=" & "more_than_three")
End If
End If
End If
End Sub
Public Sub CreateEnrollment(ByVal UserName As String, ByVal ClassDate As Date, ByVal ClassTime As String, ByVal ClassName As String, ByVal UID As Integer)
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Try
conn.Open()
Dim sql As String = "INSERT INTO EnrollmentsTbl (" & _
"[UserName],[SubmitTime],[ClassTime],[ClassDate],[Enrolled],[ClassName],[Instructor],[DateCompleted],[Completed],[WaitListed],[UID]) " & _
"VALUES (#UserName, #SubmitTime, #ClassTime, #ClassDate, #Enrolled, #ClassName, #Instructor, #DateCompleted, #Completed, #WaitListed, #UID) "
Dim comm As New Data.OleDb.OleDbCommand(sql, conn)
comm.Parameters.AddWithValue("#UserName", UserName)
comm.Parameters.AddWithValue("#SubmitTime", DateTime.Now.AddHours(3).ToString())
comm.Parameters.AddWithValue("#ClassTime", ClassTime)
comm.Parameters.AddWithValue("#ClassDate", ClassDate)
comm.Parameters.AddWithValue("#Enrolled", True)
comm.Parameters.AddWithValue("#ClassName", ClassName)
comm.Parameters.AddWithValue("#Instructor", "On-line")
comm.Parameters.AddWithValue("#DateCompleted", DateTime.Now.AddHours(3).ToString)
comm.Parameters.AddWithValue("#Completed", False)
comm.Parameters.AddWithValue("#WaitListed", False)
comm.Parameters.AddWithValue("#UID", UID)
Dim result As Integer = comm.ExecuteNonQuery()
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Sub
Public Function RecordExist(ByVal username As String) As Integer
Dim connStr As String = ConfigurationManager.AppSettings.Get(SubsiteConnString)
Dim conn As New Data.OleDb.OleDbConnection(connStr)
Dim sql As String = "SELECT COUNT(*) FROM EnrollmentsTbl " & _
"WHERE [UserName] = """ & username & """ AND ClassName LIKE """ & ClassName & """ AND [Completed] = 0 AND [Enrolled] = -1"
Dim DBCommand As New Data.OleDb.OleDbCommand(sql, conn)
Try
conn.Open()
Dim RecordCount As Integer = CInt(DBCommand.ExecuteScalar())
conn.Close()
Return RecordCount
Catch ex As Exception
Response.Write(ex)
Finally
conn.Close()
End Try
End Function
Public Function GetUID(ByVal username As String) As Integer
Dim xUserName As String = User.Identity.Name()
If (Not xUserName="") Then
Dim objConn As Data.OleDb.OleDbConnection
Dim objCmd As Data.OleDb.OleDbCommand
Dim objRdr As Data.OleDb.OleDbDataReader
Dim userAN As String
Dim strConnection As String = ConfigurationManager.ConnectionStrings("TechTrainingConn").ToString
objConn = New Data.OleDb.OleDbConnection(strConnection)
objCmd = New Data.OleDb.OleDbCommand("SELECT * FROM UsersDataTbl WHERE [UserName] = """ & xUserName & """", objConn)
Try
objConn.Open()
objRdr = objCmd.ExecuteReader()
While objRdr.Read()
userAN = objRdr.Item("UID")
End While
objRdr.Close()
objConn.Close()
Session("userID") = userAN
Return userAN
'Response.Write(Session("userAN") & " - " & xUserName)
Catch ex As Exception
Response.Write(ex)
Finally
objConn.Close()
End Try
End If
End Function
What aspx page is this supporting? I noticed you have a redirect to transcript.aspx, is this code for that page? If so that would explain the multiple page loads. Response.Redirect is not a postback so it's going to fall into recordReturned and CreateEnrollment methods again, especially if you are passing the &code=1111 in the URL querystring
I have a form that sends an email that includes 4 fields. One of the fields is validated by a custom validator against the database and if the value is found the email should send. If it is not found the email should cancel and there should be an error message. Everything is working except the email sends regardless of the validation. How can I keep the email from sending?
Imports System.Net.Mail
Imports System.Data.OleDb
Imports System.Data.SqlClient
Partial Class inforequest
Inherits System.Web.UI.Page
Protected Sub btnSend_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim mm As New MailMessage("sender#email.com", "receiver#email.com")
mm.Subject = txtSubject.Text
mm.Body = "Name: " & txtName.Text & "<br /><br />Email: " & txtEmail.Text & "<br />" & txtBody.Text & "<br /> Agent Code:" & AgentCode.Text
mm.IsBodyHtml = True
Dim smtp As New SmtpClient()
smtp.Host = "mailserver"
smtp.EnableSsl = False
Dim NetworkCred As New System.Net.NetworkCredential()
smtp.UseDefaultCredentials = False
NetworkCred.UserName = "username"
NetworkCred.Password = "password"
smtp.EnableSsl = False
smtp.Credentials = NetworkCred
smtp.Port = 587
smtp.Send(mm)
lblMessage.Text = "Email Sent SucessFully."
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim dbconn As String
Dim qstring = Request.QueryString("ID")
Dim addressDR As System.Data.SqlClient.SqlDataReader
Dim sqlcommand As String = "SELECT * FROM listings WHERE ID=#qstring"
dbconn = ConfigurationManager.ConnectionStrings("houses").ToString
Dim connection As New System.Data.SqlClient.SqlConnection(dbconn)
connection.Open()
Dim addresscmd As New System.Data.SqlClient.SqlCommand(sqlcommand, connection)
addresscmd.Parameters.AddWithValue("#qstring", qstring)
addressDR = addresscmd.ExecuteReader()
If addressDR.HasRows Then
addressDR.Read()
Me.txtBody.Text = "I would like to request a showing of the home located at: " & addressDR("address") & " MLS#: " & addressDR("mlsnum")
addressDR.Close()
End If
connection.Close()
End Sub
Protected Sub CodeValidate_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CodeValidate.ServerValidate
Dim AgentCode = Request.Form("AgentCode")
Dim sql As String = "SELECT agentcode FROM Codes WHERE agentcode = #AgentCode"
Using conn As New SqlConnection(ConfigurationManager.ConnectionStrings("Codes").ConnectionString)
Using cmd As New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("#AgentCode", AgentCode)
conn.Open()
Using rdr As SqlDataReader = cmd.ExecuteReader()
If (rdr.Read()) Then
'MsgBox("reader reading")
'If AgentCode = rdr("agentcode").ToString() Then
args.IsValid = True
'MsgBox("valid!")
Else
args.IsValid = False
'MsgBox("not valid")
End If
End Using
conn.Close()
End Using
End Using
End Sub
End Class
You need to call Page.Validate() and also check Page.IsValid
I'm kinda new to asp.net but I'm learning fast, tho I cant find any good web forms tutorial for login page written in vb, I'm using the offline application tutorials to learn and I just change the commands,
So i've come to a simple error for you guys, the problem is with the dsc.sqlclient, probably there's not such command, but what should I use?
Thanks a lot anyway!
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
' Fill the dataset
Dim ds As New DataSet()
dsc.sqlclient.sqlcommand(ds, "Users")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
Thanks a lot guys, this is the correct answer tho, kbworkshop helped me a lot!
For anyone wanna know this is the code
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
conn.Open()
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
conn.Close()
End If
End Sub
Your code should be something like this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
objConn.Open()
' Fill the dataset
Dim ds As New DataSet("Users")
Dim daExample As New SqlDataAdapter(strSQL, objConn)
daExample.Fill(ds, "Users2")
' if there no entry then the user is invalid
If ds.Tables("Users").Rows.Count = 0 Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
objConn.close()
End If
End Sub
but you can also take this:
Protected Sub btnSubmit_Click(sender As Object, e As System.EventArgs) Handles btnSubmit.Click
If Page.IsValid Then
' check for username & password in the database
Dim conn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=LoginDB;Integrated Security=True")
' Get the row corresponding the given username and password
Dim strSQL As String = "Select * From Users Where Username='" + txtUname.Text + "' and Password = '" + txtPassword.Text + "'"
'I recommend not to use * in querys
Dim dsc As New SqlClient.SqlCommand(strSQL, conn)
Dim dr As SqlDataReader
dr = dsc.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("Default.aspx")
Else
Response.Redirect("login.aspx")
End If
End If
End Sub
PLEASE don't create your SELECT statement by pasting text together.
Ugh.
Never do that.
You just allow anyone to use "SQL Injection" to log in (and worse) without a
password.
Imports System.Data
Imports System.Data.SqlClient
Partial Class log
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim cn As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=F:\WebSite1\App_Data\Database.mdf;Integrated Security=True;User Instance=True")
Dim log As String = "SELECT * FROM login WHERE userid='" & TextBox1.Text & "' AND password='" & TextBox2.Text & "'"
Session("user") = TextBox1.Text
Dim cmd As New SqlCommand(log, cn)
Dim dr As SqlDataReader
cn.Open()
dr = cmd.ExecuteReader()
If dr.HasRows = True Then
Response.Redirect("showdata.aspx")
Else
Response.Redirect("log.aspx")
End If
End Sub
End Class
You can use SqlDataAdapter class to fill your dataset:
SqlConnection conn = new SqlConnection("My ConnectionString");
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = SQL;
da.SelectCommand = cmd;
DataSet ds = new DataSet();
conn.Open();
da.Fill(ds);
conn.Close();
VB.Net:
Dim conn As New SqlConnection("My ConnectionString")
Dim da As New SqlDataAdapter()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = SQL
da.SelectCommand = cmd
Dim ds As New DataSet()
conn.Open()
da.Fill(ds)
conn.Close()
I'm trying to download files from an SQL Server 2012 database using GridView. I am getting an ArgumentOutOfRangeException giving me this error:
Index was out of range. Must be non-negative and less than the size of the collection.
on:
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Code concerned:
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
gvrow.RowIndex at time of debugging is 0.
Full Code:
Imports System.Data.SqlClient
Imports System.Data
Imports System.IO
Partial Class Documents
Inherits System.Web.UI.Page
Protected Sub btnUploadContent_Click(sender As Object, e As EventArgs) Handles btnUploadContent.Click
Dim filePath As String = FileUpload.PostedFile.FileName
Dim filename As String = Path.GetFileName(filePath)
Dim ext As String = Path.GetExtension(filename)
Dim contenttype As String = String.Empty
Select Case ext
Case ".doc"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".docx"
contenttype = "application/vnd.ms-word"
Exit Select
Case ".xls"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".xlsx"
contenttype = "application/vnd.ms-excel"
Exit Select
Case ".jpg"
contenttype = "image/jpg"
Exit Select
Case ".png"
contenttype = "image/png"
Exit Select
Case ".gif"
contenttype = "image/gif"
Exit Select
Case ".pdf"
contenttype = "application/pdf"
Exit Select
End Select
If contenttype <> String.Empty Then
Dim fs As Stream = FileUpload.PostedFile.InputStream
Dim br As New BinaryReader(fs)
Dim bytes As Byte() = br.ReadBytes(fs.Length)
'insert the file into database
Dim strQuery As String = "INSERT INTO [master_db].[dbo].[content] ([content_name],[content_type],[content_file]) VALUES (#Name, #ContentType, #Data)"
Dim cmd As New SqlCommand(strQuery)
cmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = filename
cmd.Parameters.Add("#ContentType", SqlDbType.VarChar).Value() = contenttype
cmd.Parameters.Add("#Data", SqlDbType.Binary).Value = bytes
InsertUpdateData(cmd)
lblMessage.ForeColor = System.Drawing.Color.Green
lblMessage.Text = "File Uploaded Successfully"
Else
lblMessage.ForeColor = System.Drawing.Color.Red
lblMessage.Text = "File format not recognised." + " Upload Image/Word/PDF/Excel formats"
End If
End Sub
Protected Sub lnkDownload_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim lnkbtn As LinkButton = TryCast(sender, LinkButton)
Dim gvrow As GridViewRow = TryCast(lnkbtn.NamingContainer, GridViewRow)
Dim fileid As Integer = Convert.ToInt32(GridView1.DataKeys(gvrow.RowIndex).Value.ToString())
Dim name As String, type As String
Dim con As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
con.Open()
Using cmd As New SqlCommand()
cmd.CommandText = "Select content_name, content_type, content_file from content where content_id=#Id"
cmd.Parameters.AddWithValue("#Id", fileid)
cmd.Connection = con
con.Open()
Dim dt As DataTable = GetData(cmd)
If dt IsNot Nothing Then
download(dt)
End If
End Using
End Sub
Public Function GetData(ByVal cmd As SqlCommand) As DataTable
Dim dt As New DataTable
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim con As New SqlConnection(strConnString)
Dim sda As New SqlDataAdapter
cmd.CommandType = CommandType.Text
cmd.Connection = con
Try
con.Open()
sda.SelectCommand = cmd
sda.Fill(dt)
Return dt
Catch ex As Exception
Response.Write(ex.Message)
Return Nothing
Finally
con.Close()
sda.Dispose()
con.Dispose()
End Try
End Function
Protected Sub download(ByVal dt As DataTable)
Dim bytes() As Byte = CType(dt.Rows(0)("Data"), Byte())
Response.Buffer = True
Response.Charset = ""
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Response.ContentType = dt.Rows(0)("ContentType").ToString()
Response.AddHeader("content-disposition", "attachment;filename=" & dt.Rows(0)("Name").ToString())
Response.BinaryWrite(bytes)
Response.Flush()
Response.End()
End Sub
Public Function InsertUpdateData(ByVal cmd As SqlCommand) As Boolean
Dim strConnString As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnStringDb1").ConnectionString()
Dim conn As New SqlConnection("Data Source=BRIAN-PC\SQLEXPRESS;Initial Catalog=master_db;Integrated Security=True;")
cmd.CommandType = CommandType.Text
cmd.Connection = conn
Try
conn.Open()
cmd.ExecuteNonQuery()
Return True
Catch ex As Exception
Response.Write(ex.Message)
Return False
Finally
conn.Close()
conn.Dispose()
End Try
End Function
End Class
What is happening and why?
replace the error line with this:
Dim selectedRow As Integer = Me.GridView1.CurrentRow.Index
Dim fileid As Integer = Convert.ToInt32(Me.GridView1.Item(1,gvrow.RowIndex).Value.ToString())
Replace the number 1 with the index of the cell that contains the fileid (ie if its the 0 for the first cell, 1 for the second and so on)
Let me know if this works. Am a C# developer so conversions may differ.
pass the RowIndex via CommandArgument and use it to retrieve the DataKey value
add the below line on Button
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
and add the below line on Server Event
Dim Index As Integer = Integer.Parse(e.CommandArgument.ToString())
Dim val As String = DirectCast(Me.grid.DataKeys(Index)("YourDataKeyName"), String)
Update:
See this samples :
sample1
sample 2
I ran into this a while ago myself replacing a predecessors data adapter's with data readers for obvious reasons.
My fix was simple:
if (dt.Rows.Count == 0)
//do stuff
else
//do nothing
GV.DataSource = new DataTable();
you're also loading with a datatable, so that should make deploying it easier.
The reason in your specific case is the exception is thrown when no data is passed to the GV.
I am trying to work out SQL code in VB but I am having problems I have a simple database with the table admin with the columns UserName and Password.
I want to be able to read data from a text box and then input it into a SQL string… the SQL string works (I've tested it) and I can get it to output with a simple SELECT statement but I can't seem to get the SQL to read my Parameter.
Help?
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Call Password_Check(txtTestInput.Text)
End Sub
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", Answer)
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
in your code above:
--> Dim parameter As New SqlParameter("#Username", Answer)
Can I suggest two options:
Dim parameter As New SqlParameter("#Username", sqldbtype.nvarchar)
parameter.value = Answer
or
cmd.CommandText = string.format("SELECT Password FROM Admin WHERE (UserName = {0})", Answer)
Full Code:
Public Sub Password_Check(ByVal Answer As String)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Dim parameter As New SqlParameter("#Username", SqlDbType.NVarChar)
parameter.Value = Answer
Try
con.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("Database1ConnectionString1").ConnectionString
con.Open()
cmd.Connection = con
cmd.CommandText = "SELECT Password FROM Admin WHERE (UserName = #Username)"
cmd.Parameters.Add(parameter)
Dim lrd As SqlDataReader = cmd.ExecuteReader()
While lrd.Read()
Dim sothing As String
sothing = lrd("Password").ToString
If lrd("Password").ToString = txtPassword.Text Then
lblTestData.Text = "passwordSuccess"
ElseIf lrd("Password").ToString <> txtPassword.Text Then
lblTestData.Text = "passwordFail...:("
End If
End While
Catch ex As Exception
lblTestData.Text = "Error while retrieving records on table..." & ex.Message
Finally
con.Close()
End Try
End Sub
Regarding to your Database system it is possible that it does not support parameter names. Have you tried ? Wat DB System you used?
cmd.CommandText = " SELECT Password FROM Admin WHERE (UserName = ?)"