I have an edit profile page where the user can edit their profile information. At the minute, new users cannot use this page as they have not got a corresponding record in the 'userprofiles' table. I am using the aspnet_ membership system with corresponding aspnet_User tables in the same database. There is no link between 'userprofiles' and the aspnet tables
I have a sub called 'DisplayData()' that checks if there is a record for the user in the table and displays their profile information in the textboxes. Unfortunately, for new users, there is no record in the table so it throws an error
Here is my Page_Load sub:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Session("userName") = User.Identity.Name
Dim conn As New OleDb.OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
conn.Open()
Dim cmdcheck As New OleDbCommand("SELECT TravellerName FROM userprofiles WHERE (TravellerName = ?) ", conn)
cmdcheck.Parameters.AddWithValue("#userName", Session("userName"))
Dim profileCheckDr = cmdcheck.ExecuteReader()
If IsDBNull(profileCheckDr("TravellerName")) Then
??
End If
If Not IsPostBack Then
DisplayData()
savec.Visible = False
End If
End Sub
And here is my DisplayData() function which inputs all current user profile information into the textboxes on the page:
Protected Sub DisplayData()
Dim conn As OleDbConnection = New OleDbConnection(ConfigurationManager.ConnectionStrings("BookMeetConnString").ConnectionString)
Dim sql = "SELECT * FROM userprofiles WHERE TravellerName=#f1"
Dim cmd = New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#f1", User.Identity.Name)
conn.Open()
Dim profileDr = cmd.ExecuteReader()
profileDr.Read()
Dim newEmailAddress = ""
Dim newDescription = ""
Dim newDOB = ""
Dim newLocation = ""
Dim newProfession = ""
Dim newSmoker = ""
Dim newDrinker = ""
Dim newEducationLevel = ""
Dim newMaritalStatus = ""
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
If Not IsDBNull(profileDr("EmailAddress")) Then newEmailAddress = profileDr.Item("EmailAddress")
If Not IsDBNull(profileDr("DOB")) Then newDOB = profileDr.Item("DOB")
If Not IsDBNull(profileDr("Location")) Then newLocation = profileDr.Item("Location")
If Not IsDBNull(profileDr("Description")) Then newDescription = profileDr.Item("Description")
If Not IsDBNull(profileDr("Profession")) Then newProfession = profileDr.Item("Profession")
If Not IsDBNull(profileDr("Smoker")) Then newSmoker = profileDr.Item("Smoker")
If Not IsDBNull(profileDr("Drinker")) Then newDrinker = profileDr.Item("Drinker")
If Not IsDBNull(profileDr("EducationLevel")) Then newEducationLevel = profileDr.Item("EducationLevel")
If Not IsDBNull(profileDr("MaritalStatus")) Then newMaritalStatus = profileDr.Item("MaritalStatus")
If Not IsDBNull(profileDr("AvatarURL")) Then ProfilePic.ImageUrl = profileDr.Item("AvatarURL")
description.Text = newDescription
email.Text = newEmailAddress
smoker.SelectedValue = newSmoker
drinker.SelectedValue = newDrinker
dd_userlocation.SelectedValue = newLocation
dob.Text = newDOB
educationlevel.SelectedValue = newEducationLevel
profession.SelectedValue = newProfession
maritalstatus.SelectedValue = newMaritalStatus
conn.Close()
End Sub
How do I break out of the Page Load sub so that the DisplayData() sub doesn't run if the results of the query in the Page Load sub do not return anything. I've already tried using 'Exit Sub' but it doesn't seem to work.
A quick fix would be to simply move your If statement to surround the call to DisplayData:
If Not IsPostback Then
If Not IsDBNull(profileCheckDr("TravellerName")) Then
DisplayData()
End If
End If
However, the real question is - if the user has not registered for your site yet, how are they even able to get to the Edit Profile page? Unregistered users should not be able to get to user-specific parts of your site.
Related
I want to get the sum of the selected items in the listbox and display them in a label but i am always getting 0,i also want to put the selected items in another label too which is also not working.
Here is what the code look like:
Dim sum As Integer
Dim Items1 As String = "None"
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
Dim connetionString As String = Nothing
Dim connection As SqlConnection
Dim command As SqlCommand
Dim adapter As New SqlDataAdapter()
Dim ds As New DataSet()
Dim sql As String
connetionString = "Data Source=.;Initial Catalog=Shop;integrated security=true"
sql = "select PhoneName,PhonePrice from SmartPhones"
connection = New SqlConnection(connetionString)
connection.Open()
command = New SqlCommand(sql, connection)
adapter.SelectCommand = command
adapter.Fill(ds)
adapter.Dispose()
command.Dispose()
connection.Close()
ListBox1.DataSource = ds.Tables(0)
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
code where the display should happen:
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles TotalPrice.Click
sum = 0 'reset sum to 0
For Each i As Integer In ListBox1.GetSelectedIndices
Dim CurrentItem As ListItem = ListBox1.Items(i)
sum = sum + CInt(CurrentItem.Value)
Items1 = Items1 + " , " + CStr(CurrentItem.Text)
Next
Label3.Text = Items1
Label1.Text = sum
End Sub
Here is the page Design and the Page On the web Respectively:
PhoneName is of type varchar in database & PhonePrice is of type integer (Both Filled correctly).
ListBox code:
<asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple" ></asp:ListBox>
What's the reason that the code won't give me the desired result?
What is happening is that when you click TotalPrice a postback is performed (What is a postback?). If you look at the ASP.NET page lifecycle you will see that the Load event happens before the postback event handling (e.g. your Sub Button2_Click).
So, you click the button, it runs the Me.Load handler and... your list is reset before the click handler gets a chance to run.
There is a property you can check to see if the page is running as a result of a postback: Page.IsPostBack.
So all you need to do is check it to see if you need to populate the list:
Sub FillItemsList()
Dim connectionString As String = "Data Source=.;Initial Catalog=Shop;integrated security=true"
Dim dt As New DataTable()
Using connection As New SqlConnection(connectionString)
Dim sql As String = "SELECT PhoneName,PhonePrice FROM SmartPhones"
Using adapter As New SqlDataAdapter(sql, connection)
adapter.Fill(dt)
End Using
End Using
ListBox1.DataSource = dt
ListBox1.DataTextField = "PhoneName"
ListBox1.DataValueField = "PhonePrice"
ListBox1.DataBind()
End Sub
Private Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
Label2.Text = Request.QueryString("Name").ToString()
If Not Page.IsPostBack Then
FillItemsList()
End If
End Sub
I have masterpage & content page. In master Page I have DropDownList of Cities which Gets cities from database. And in my content page I DropDownList Of Areas which also comes from database. Now Suppose If My city gets changed then desire area related to that particular selected city should also get changed. I have manage my db tables properly & passing correct query as well. But DropDownList Of areas doesn't gets refreshed if City DropDownList gets changed. Following code I am trying.
MasterPage
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
Me.PopulateCities()
If Not IsPostBack Then
If Session("masterLocation") Is Nothing Then
Session("cityName") = "Pune"
Else
locationSelector.Text = Session("masterLocation").ToString()
End If
End If
locationPopupActivator.Text = locationSelector.SelectedValue.ToString
End Sub
Private Sub PopulateCities()
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select cityName from cities where status = 'active' order by cityName"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("cityName").ToString()
item.Value = sdr("cityName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
locationSelector.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
End Sub
ContentPage
Private Sub hospitals_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
If Not IsPostBack Then
Me.PopulateAreas()
End If
End Sub
Private Sub PopulateAreas()
areasList.Items.Clear()
Dim citySelector As RadioButtonList = Page.Master.FindControl("locationSelector")
Using conn As New MySqlConnection()
conn.ConnectionString = ConfigurationManager _
.ConnectionStrings("conio").ConnectionString()
Using cmd As New MySqlCommand()
cmd.CommandText = "Select * from areas where areaCity like '" + citySelector.SelectedItem.ToString + "%'"
cmd.Connection = conn
conn.Open()
Using sdr As MySqlDataReader = cmd.ExecuteReader()
While sdr.Read()
Dim item As New ListItem()
item.Text = sdr("areaName").ToString()
item.Value = sdr("areaName").ToString()
'item.Selected = Convert.ToBoolean(sdr("IsSelected"))
areasList.Items.Add(item)
End While
End Using
conn.Close()
End Using
End Using
areasList.Items.Insert(0, New ListItem("All Area", "All"))
End Sub
Everything in your code is fine just make changes On Pre_Render event of your content page
If IsPostBack Then
Me.PopulateAreas()
End If
Make this changes. Hope this will solve your problem.
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
I have a page with a very distinct layout with 36 textboxes laid out using a table so that it reflects the layout of an exhibit hall and what exhibit tables can be reserved. I have been able save them all to the database seamlessly by looping through the form keys like this:
Protected Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
Dim tbname As String = ""
Dim vendorName As String = ""
Dim formkey As String = ""
Dim conn As New SqlConnection(ConnectionStrings.Item("WebDB").ConnectionString)
Dim cmd As New SqlCommand("UPDATE FloorPlan SET VendorName = #VendorName WHERE tbName = #tbName", conn)
conn.Open()
For Each o As Object In Request.Form.Keys
formkey = o.ToString.Replace("ctl00$ContentPlaceHolder1$", "")
If Left(formkey, 2) = "tb" Then
tbname = formkey
vendorName = Request(o.ToString)
cmd.Parameters.AddWithValue("#VendorName", vendorName)
cmd.Parameters.AddWithValue("#tbName", tbname)
cmd.ExecuteNonQuery()
cmd.Parameters.Clear()
tbname = ""
vendorName = ""
End If
Next
conn.Close()
conn.Dispose()
End Sub
I can't figure out how to load the values on page load dynamically where it would locate the textbox id on the page and fill in the value.
I have tried things like this:
For Each r In ds1.Tables("SE").Rows
CType(FindControl(r("tbname")), TextBox).Text = r("vendorname")
Next
but I just get the "object reference not set to an instance..." error. What approach should I take to get the values loaded properly without hard-coding tb1.text = "blah", tb2.text = "acme", etc...
Perhaps it has to do with nested controls or master pages? Could try Atwood's recursive find control: stackoverflow.com/questions/1457567/c-findcontrol
I'm trying to increment my variable on a button click. It increments only once. It seems as though it's getting lost when it reloads the page.
I'm using the following code:
Dim ItemSelect As New ArrayList()
Dim Quantities As New ArrayList()
Dim itemQtyOrdered As Integer
Public Sub ShtickDataList_ItemCommand(ByVal source As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ShtickDataList.ItemCommand
If e.CommandName = "ViewCart" Then
Response.Redirect("~/ShoppingCart.aspx")
End If
If e.CommandName = "addToCart" Then
Dim itemQuantity As DropDownList = e.Item.FindControl("QuantityDropDown")
itemQtyOrdered = itemQuantity.SelectedValue
ItemSelect.Add(e.CommandArgument)
Quantities.Add(itemQtyOrdered)
Session("itemInCart") = ItemSelect
Session("quantities") = Quantities
viewInvoice()
End If
End Sub
Protected Sub viewInvoice()
Dim itemSelected As ArrayList = DirectCast(Session("itemInCart"), ArrayList)
Dim QuantityofItem As ArrayList = DirectCast(Session("quantities"), ArrayList)
Dim conn As SqlConnection
Dim comm As SqlCommand
Dim reader As SqlDataReader
Dim purimConnection2 As String = ConfigurationManager.ConnectionStrings("Purim").ConnectionString
conn = New SqlConnection(purimConnection2)
comm = New SqlCommand("SELECT ProductName FROM Products WHERE ProductID = #ProductID", conn)
Dim i As Integer
For i = 0 To ItemSelect.Count - 1
comm.Parameters.Add("#ProductID", Data.SqlDbType.Int)
comm.Parameters("#ProductID").Value = ItemSelect(i)
Next
Try
conn.Open()
reader = comm.ExecuteReader()
ViewCartlink.Text = "View Cart: (" & ItemSelect.Count & ")"
Finally
conn.Close()
End Try
End Sub
Ah, you may be referring to ItemSelect and Quantities lists. You need to look for them in Session and only create them if they are not in the Session. I am rusty on VB.NET, so this is C# version. In Page_Load:
ItemSelect = (ArrayList)Session["itemInCart"];
if (ItemSelect == null)
{
ItemSelect = new ArrayList();
Session["itemInCart"] = ItemSelect;
}
and the same for Quantities.
Also, your loop in viewInvoice method is wrong. For more than one item in ItemSelect list you are adding multiple parameters with the same name. You probably only wanted to do it once with
comm.Parameters("#ProductID").Value = ItemSelect(ItemSelect.Count - 1)