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
Related
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.
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)
As you can see from the commented out code, I'm trying to get the model dropdown be affected by + selCurrentManuf.Text.
I get this error
'selCurrentManuf' is not declared. It may be inaccessible due to its protection level.
How can this be solved?
I can access the drop down in another part of the page like this..
Dim sc1_currentmanuf As String = CType(e.Item.FindControl("selCurrentManuf"), DropDownList).Text
However in the function i am trying to use selCurrentManuf does not have access to e
Dim sc1_currentmanuf As String = CType(dlContacts.Items(0).FindControl("selCurrentManuf"), DropDownList).Text
Dim myQuery As String = "SELECT * FROM c5_model where c5_manufid = " + sc1_currentmanuf
Right click on your .aspx page, and select the command Convert To Web Application.
Then you'll be able to write:
Dim myQuery As String =
String.Format("SELECT * FROM c5_model WHERE c5_manuf = '{0}'",
selCurrentManuf.SelectedItem.Text )
I'm assuming your functions are inside a class in your App_Code or another dll and not on the code behind of the page.
If so do this instead:
I'm assuming you have something like this on your asp page code behind:
Protected Sub selCurrentManuf_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetCurrentModel(selCurrentManuf.Text)
End Sub
Change Your GetCurrentModel Code To:
Function GetCurrentModel(Byval c5_manuf as String) As DataSet
Dim mySession = System.Web.HttpContext.Current.Session
Dim myQuery As String = "SELECT * FROM c5_model " 'where c5_manuf = " + + c5_manuf
Dim myConnection As New MySqlConnection(mySession("localConn"))
myConnection.Open()
Dim myCommand As New MySqlCommand(myQuery, myConnection)
Dim myDataAdapter = New MySqlDataAdapter(myCommand)
Dim myDataset As New DataSet
myDataAdapter.Fill(myDataset, "c5_model")
Dim dr As DataRow = myDataset.Tables(0).NewRow
myDataset.Tables(0).Rows.Add(dr)
GetCurrentModel = myDataset
myConnection.Close()
End Function
Protected Sub GridView1_RowCommand _
(sender As Object, e As GridViewCommandEventArgs) _
Handles GridView1.RowCommand
If e.CommandName.CompareTo("command") = 0 Then
Dim itemID As Integer = Convert.ToInt32( _
GridView1.DataKeys(Convert.ToInt32(e.CommandArgument)).Value)
Dim sqlConn As New SqlConnection("connectionString")
sqlConn.Open()
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = '" + itemID + "', sqlConn")
sqlComm.ExecuteNonQuery()
sqlConn.Close()
End If
End Sub
Basically, it doesn't work and I don't get it. I've been trying to figure this out for a few days now and I can't see what I've done wrong. As you can see I'm trying to manually update a field in my database with the value of (originalvalue)+1 when the user clicks the buttonfield of the corresponding row.
I guess what I'm asking is if anyone can point out any mistakes, please do, or if there's a better way to do this (without having to go through all the DAL/BLL BS) please tell it to me.
Thank you very much!
I've solved my own problem! Look at the code:
Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
If e.CommandName = "commandname" Then
// Convert the row index stored in the CommandArgument
// property to an Integer.
Dim index = Convert.ToInt32(e.CommandArgument)
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
Dim row = GridView1.Rows(index)
// Calculate the new value.
Dim tb = CType(row.FindControl("Label1"), Label)
Dim newint As Integer = Convert.ToDouble(tb.Text) + 1
// Get the id of the idea.
Dim id As Integer = Convert.ToInt32( _
GridView1.DataKeys(index).Value)
//Manual update to the database.
Dim con As New SqlConnection("connectionstring")
Dim cmd As New SqlCommand("UPDATE ideatable SET field = " & (newint.ToString) & " WHERE id = " & (id.ToString), con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
//Refresh the page.
Page.Response.Redirect("default.aspx")
End If
End Sub
And remember to set OnRowCommand="GridView1_RowCommand" for the gridview in the aspx file code too, I forgot about that earlier! :/
I'm so happy, thanks for all the help offered! Hope this answer helps someone like me who got stuck.
I think there is problem in your sentence :- Try Below one at place of your Statement
Dim sqlComm As New SqlCommand("UPDATE itemTable SET property = (property + 1) WHERE id = " + itemID + "", sqlConn)
Watch the string you are generating and try to execute it manually and then what happens the table gets UPDATE or not.
Because I Think The "ItemId" is not there in your table.
Try to do This in SQL Server "Select * From itemTable Where id = ItemId" Because i think that the itemId is not there in your table.
I HAVE EDITED THIS BUT THE SAME PROBLEM :
Protected Sub SqlDataSource1_Updated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
For Each myRow As GridViewRow In GridView1.Rows
'Find the checkbox
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
Try
Using conn = New SqlConnection(constr)
Using cmd = conn.CreateCommand()
conn.Open()
Dim sql As String = "UPDATE a1_ticket SET Travels = #travels WHERE travelid = #travelid"
cmd.CommandText = sql
cmd.Parameters.AddWithValue("#travels", lab4.Text)
cmd.Parameters.AddWithValue("#travelid", lab1.Text)
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
Response.Write(ex.Message)
End Try
Next
End Sub
ERROR : OBJECT REFERENCE IS NOT SET TO THE INSTANCE OF AN OBJECT
Error is in this line : Dim strSql As String = "UPDATE a1_ticket SET Travels = '" & lab4.Text & "' WHERE travelid =" & lab1.Text
travelid is Text so it should be travelid='" & lab4.Text & "'".
I strongly suspect that this is going to be the culprit:
Dim lab1 As Label = DirectCast(myRow.FindControl("Label1"), Label)
Dim lab4 As Label = DirectCast(myRow.FindControl("Label4"), Label)
FindControl returns null/Nothing if it can't find a control with that ID. My guess is that because you've got potentially multiple rows, the IDs of the controls within each row are autogenerated with extra information. I suggest you look at the HTML on the page and see what's being generated... you may want to look at finding a better way of finding an individual control within a row.
As mentioned in comments, you should then parameterize your SQL statements to avoid SQL injection attacks.