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
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
Hi people I am trying to carry a session variable for my login control which i am using to pass to pass to another page and display their details. I am using the aspNetDB. My username has been set to an integer as is connected to another database table displaying the users details below is my code:
Protected Sub Login1_LoggingIn(sender As Object, e As System.Web.UI.WebControls.LoginCancelEventArgs) Handles Login1.LoggingIn
Session("StaffNo") = Login1.UserName()
End Sub
The code is then being sent to my other page to display their details when loaded on a data grid but the session does not seem to be carrying:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
Dim Staff As String = CType(Session.Item("StaffNo"), String)
Dim conn As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "SELECT * FROM [User] WHERE studentnum = #StaffNo"
conn = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, conn)
cmd.Parameters.Add("#StaffNo", SqlDbType.Char).Value = Staff
conn.Open()
Dim myReader As SqlDataReader
myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection)
GridView1.DataSource = myReader
GridView1.DataBind()
conn.Close()
Catch ex As Exception
Response.Write("An error has occurred")
End Try
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Try
Dim cmdstring As String = "SELECT * FROM [User] WHERE studentnum = '"& Session("StaffNo").ToString & "' "
End Sub
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)
I can't see why this is not working.
I have a dropdownlist named ddlRoomName and a SQL table named roomlist.
When i run the SQL command in SQL editor it works fine. But when I load the page the rooms do not load!
Am i missing something obvious here?
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack Then
ddlRoomName.Items.Clear()
ddlRoomName.Items.Add(New ListItem("--Select Room--", ""))
ddlRoomName.AppendDataBoundItems = True
Dim strConnString As String = ConfigurationManager.ConnectionStrings("a_cisco").ConnectionString
Dim strQuery As String = "Select * from roomlist"
Dim con As New SqlConnection(strConnString)
Dim cmd As New SqlCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText = strQuery
cmd.Connection = con
Try
con.Open()
ddlRoomName.DataSource = cmd.ExecuteReader()
ddlRoomName.DataTextField = "RoomName"
ddlRoomName.DataValueField = "intRoom"
ddlRoomName.DataBind()
Catch ex As Exception
Throw ex
Finally
con.Close()
End Try
End If
End Sub
You are only loading them on a postback. Is it really what you want? Maybe you want:
If Not Page.IsPostBack Then
End If
(then the ViewState will keep the items in the DropDownList in a postback)