I am making Log in page for my project but I am getting an error "There is no row at position 0" while running.
I tried these lines of codes.
Imports System.Data.SqlClient
Imports System.Data
Partial Class Dept_login
Inherits System.Web.UI.Page
Protected Sub BtnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnSubmit.Click
Dim ds As New DataSet
'Try
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("VMSConnectionString").ConnectionString)
con.Open()
Dim cmd As New SqlCommand("SELECT password FROM Dept_login WHERE user_id='" + Txtuname.Text + "'", con)
Dim da As New SqlDataAdapter(cmd)
da.Fill(ds)
If Not IsDBNull(ds) Then
If Txtpwd.Text = ds.Tables(0).Rows(0).Item("password") Then
Response.Redirect("Online Services.aspx") 'the page i want to redirect to after login successful
Else
Label1.Visible = True 'initially visible is false and text is INVALID PASSWORD
End If
con.Close()
' Catch ex As Exception
' End Try
End If
End Sub
Private Function Dept_login() As Integer
Throw New NotImplementedException
End Function
End Class
This line doesn't make sense:
If Not IsDBNull(ds) Then
ds will never be DBNull. Instead, check for the number of rows coming back, like:
If ds.Tables(0).Rows.Length > 0 Then
You're trying to get the first row (.Rows(0)) when there aren't any - that's what the error is telling you.
Try using something like this:
If ds.Tables(0).Rows.Count > 0 AndAlso Txtpwd.Text = ds.Tables(0).Rows(0).Item("password") Then
Response.Redirect("Online Services.aspx", False) 'the page i want to redirect to after login successful
Context.ApplicationInstance.CompleteRequest();
Else
Label1.Visible = True 'initially visible is false and text is INVALID PASSWORD
End If
con.Close()
' Catch ex As Exception
' End Try
(Note: You should use parameterization for the SQL query. You're leaving yourself open to a SQL injection attack.)
This line doesn't make sense:
If Not IsDBNull(ds) Then
Makes sense
If ds.Tables(0).Rows.count > 0 andalso ds.Tables..count > 0 Then
END IF
Hope this helps
Did you try using a datareader instead of a dataadapter?
Try
Dim datare As SqlDataReader
Using cn As New SqlConnection(ConfigurationManager.ConnectionStrings("VMSConnectionString").ConnectionString)
Using cmd As New SqlCommand("SELECT password FROM Dept_login WHERE user_id='#User'", cn)
cmd.Parameters.AddWithValue("#User", Txtuname.Text)
cn.Open()
datare = cmd.ExecuteReader()
With datare
If .Read() Then
If .Item(0) = txtpwd.Text Then
Response.Redirect("Online Services.aspx")
Else
Label1.Visible = True
End If
End If
End With
End Using
End Using
Catch ex As Exception
Throw ex
End Try
Also, on the query you write user_id. did you mean username? Is you query correct?
Related
I am having an issue with my login page. I am not getting any errors so am not able to know where the problem is?
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Login.Click
'connection string
Dim mysqlconn As MySqlConnection = New MySqlConnection("server=localhost;user id=root;Password=123;database=users;persist security info=False")
Dim cmd As New MySqlCommand
Dim da As New MySqlDataAdapter
Dim mydata As New DataTable
Dim reader As MySqlDataReader
Try
mysqlconn.Open()
Dim query As String
query = "SELECT * FROM login_form where Username = '" & rfvUser.Text & "' and Password='" & rfvPWD.Text & "'"
cmd = New MySqlCommand(query, mysqlconn)
reader = cmd.ExecuteReader
While reader.Read()
If rfvUser.Text = "admin" And rfvPWD.Text = "admin" Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Admin.aspx")
ElseIf (rfvUser.Text = reader("UserName").ToString()) And (rfvPWD.Text = reader("Password").ToString()) Then
Me.Session("User") = Me.rfvUser.Text
Server.Transfer("Ersal_send.aspx")
Else
ClientScript.RegisterStartupScript(Page.[GetType](), "validation", "<script language='javascript'>alert('Invalid Username or Password')</script>")
reader.Close()
End If
End While
Catch ex As Exception
MsgBox(ex.Message)
Finally
mysqlconn.Dispose()
End Try
End Sub
End Class
Have you tried running the query directly via a SQL client? If your query is not returning any rows, then your procedure will simply exit without any errors as it will never enter the While loop.
Another advice: It is never a good idea to pass user input directly into a query. This leads to SQL injection. Use parameterised queries. Google for it.
I select values from database into textboxes on page load. Then when I change them and want to update the database, values are same as original values. For example I select name Robin Hood into TextBoxName, change it to Bill Gates, but the value of textbox on updating is still Robin Hood. How can I fix this behavior?
However this applies only to textboxes with TextMode="SingleLIne" Or "MultiLine". When textbox has TextMode="Url" for example, it works fine.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Bind
Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "SELECT * FROM Profiles WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
Dim rd As SqlDataReader = cmd.ExecuteReader()
While rd.Read()
ProfileImage.ImageUrl = rd.Item("ProPicUrl")
txtName.Text = rd.Item("Name")
txtCity.Text = rd.Item("City")
drpRegion.Items.FindByText(rd.Item("Region")).Selected = True
txtAge.Text = rd.Item("Age")
RadioButtonList1.Items.FindByText(rd.Item("Sex")).Selected = True
txtLink.Text = rd.Item("Link")
txtPhone.Text = rd.Item("Phone")
txtAbout.Text = rd.Item("About")
txtMotto.Text = rd.Item("Motto")
txtGoal.Text = rd.Item("Goal")
txtHobby.Text = rd.Item("Hobby")
End While
conn.Close()
End Using
Catch ex As Exception
End Try
End Sub
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Dim fileUrl As String = "~/ProPics/"
Dim name As String = txtName.Text
Try
'Save profile picture
Try
If FileUpload1.HasFile Then
fileUrl += FileUpload1.FileName
FileUpload1.SaveAs(Server.MapPath(fileUrl))
Else
fileUrl = ProfileImage.ImageUrl
End If
Catch ex As Exception
UploadMessage.Text = "Nastala chyba při nahrávání obrázku." + vbCrLf + "Chybové hlášení: " + ex.Message
End Try
Using conn As New SqlConnection(connStr)
Dim cmd As SqlCommand = conn.CreateCommand
cmd.CommandText = "UPDATE Profiles SET Name = #Name, ProPicUrl = #Url, City = #City, Region = #Region, Age = #Age, Sex = #Sex, Link = #Link, Phone = #Phone, About = #About, Motto = #Motto, Goal = #Goal, Hobby = #Hobby WHERE (ProfileId = #ProfileId)"
cmd.Parameters.AddWithValue("#Url", fileUrl)
cmd.Parameters.AddWithValue("#Name", name)
cmd.Parameters.AddWithValue("#City", txtCity.Text)
cmd.Parameters.AddWithValue("#Region", drpRegion.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Age", txtAge.Text)
cmd.Parameters.AddWithValue("#Sex", RadioButtonList1.SelectedItem.Text)
cmd.Parameters.AddWithValue("#Phone", txtPhone.Text)
cmd.Parameters.AddWithValue("#Link", txtLink.Text)
cmd.Parameters.AddWithValue("#About", txtAbout.Text)
cmd.Parameters.AddWithValue("#Motto", txtMotto.Text)
cmd.Parameters.AddWithValue("#Goal", txtGoal.Text)
cmd.Parameters.AddWithValue("#Hobby", txtHobby.Text)
cmd.Parameters.AddWithValue("#ProfileId", Request.QueryString("id"))
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
'Refresh page
Response.Redirect(Request.RawUrl)
End Using
Catch ex As Exception
End Try
End Sub
You need to add a check for IsPostBack property of the page when you execute code in the Page_Load event.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
if Not PostBack Then
...... code to execute only the first time the Page_Load is called
Try
End Try
Catch ex As Exception
End Try
End If
.. code to execute every time....
End Sub
When your user clicks on a button with Runat=Server then the button calls the event on the server side code, but this cause a new call to Page_Load.
Actually your code reloads from the database the original value everytime the Page_Load event executes and thus your button click event code sees the original value from the database instead of the modified value.
This article on the Page Life Cycle could be useful here
Hey everyone I am trying to figure out how to re write a url such as www.mywebsit.com/Articles/newsInfo.aspx?id=3 to www.mywebisite.com/Articles/My-News-Title.aspx
I don't know if I am misunderstanding something but below is the code i have and nothing seems to be happening. The URL stays the same.
Sub Application_BeginRequest(ByVal sender As Object, ByVal e As EventArgs)
Dim currPath As String = Request.Url.ToString
If currPath.IndexOf("Articles") <> -1 And currPath.IndexOf("?np=") <> -1 Then
currPath = currPath.Substring(currPath.IndexOf("?np=") + 4)
Dim connectionString As String = ConfigurationManager.ConnectionStrings("MyConString").ConnectionString
Dim myreader As System.Data.SqlClient.SqlDataReader
Using myConnection As New System.Data.SqlClient.SqlConnection(connectionString)
Try
myConnection.Open()
Dim myCommand As New System.Data.SqlClient.SqlCommand()
myCommand.CommandType = Data.CommandType.Text
myCommand.CommandText = "SELECT TheNewsTitle FROM TheNews WHERE TheNewsId=" & currPath.Replace("'", "''")
myCommand.Connection = myConnection
myreader = myCommand.ExecuteReader
If myreader.HasRows Then
myreader.Read()
HttpContext.Current.RewritePath("~/Articles/" & myreader.GetValue(0).ToString.Replace(" ", "-") & ".aspx")
myreader.Close()
End If
myConnection.Close()
myCommand.Dispose()
myConnection.Dispose()
Catch ex As Exception
myConnection.Close()
myConnection.Dispose()
End Try
End Using
End If
End Sub
The code never errors out so i don't understand what is going on.
Are you trying to do actual URL Rewriting ? In other words - you want the links in your site to look like
www.mywebsite.com/Articles/My-News-Title.aspx
and be processed by
www.mywebsite.com/Articles/newsInfo.aspx?id=3
yes ?
Have a look here: -
http://msdn.microsoft.com/en-us/library/cc668201.aspx
http://msdn.microsoft.com/en-us/library/dd329551.aspx
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)
In codebehind I have the following:
Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSubmit.Click
Dim sql As String
Dim conn As OleDbConnection
Dim cmd As OleDbDataAdapter
Dim ds As DataSet
Dim tbl As DataTable
conn = New OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
cmd = New OleDbDataAdapter(sql, conn)
ds = New DataSet
cmd.Fill(ds)
tbl = New DataTable
tbl = ds.Tables(0)
If tbl.Rows.Count = 0 Then
Response.Redirect("goback.html")
End If
Response.Redirect("dummy.html")
Catch ex As Exception
Response.Redirect("goback2.html")
End Try
End Sub
The routine works to a point. I can check the value of tbl.Rows.Count = 1, so it should redirect to "dummy.html" WHICH IT DOES CORRECTLY so long as I comment out the line that redirects to "goback2.html".
If I uncomment the line to redirect to goback2, then it goes to "goback2.html"
I thought it should only execute that code if there was some error in the previous code - but there can't be an error in the previous code, if it executes. It's like it's executing the catch code regardless of what I'm going.
Oddly, it ONLY messes up with the redirect! If I replace the redirect to goback2 with an assignment to a textbox.text then it works (by ignoring that code) - but the redirect it seems to execute regardless of whether it should take the catch
Response.Redirect(string) throws a ThreadAbortException when Response.End() is called.
Use the overload that takes a string and a boolean instead:
Response.Redirect("goback.html", false);
From MSDN: the second parameter, endResponse, "Indicates whether execution of the current page should terminate."
Response.Redirect throws a ThreadAbortException to terminate the current request.
Your Catch block is catching that exception.
It may be because of ThreadAbortedException because of Response.Redirect. - MSDN support link
You haven't open the connection. You cannot redirect in an Try/Catch. You should set a boolean variable success to false and check for it after the Try/Catch/Finally and redirect if it's set to false.
Have a look at this SO-Question: Is there something that prevents Response.Redirect to work inside try-catch block?
This would be better:
Dim success As Boolean = True
Dim ds As New DataSet
Using conn As New OleDb.OleDbConnection("Provider=SQLOLEDB;Data Source=(local);Initial Catalog='library';Integrated Security=SSPI;")
Try
Dim Sql = "SELECT f1, f2, f3 FROM mydb WHERE ltrim(rtrim(UPPER(username))) = 'MYNAME'"
Dim cmd = New OleDb.OleDbDataAdapter(Sql, conn)
conn.Open()
cmd.Fill(ds)
Catch ex As Exception
success = False
End Try
End Using
If Not success Then
Response.Redirect("goback2.html")
ElseIf ds.Tables.Count <> 0 AndAlso ds.Tables(0).Rows.Count = 0 Then
Response.Redirect("goback.html")
Else
Response.Redirect("dummy.html")
End If