change textbox's value from pageload event, submit new values issue - asp.net

I have created a form to update an access DB table. My issue is that when the text in the text boxes is changed and the form is submitted, the .text values stay the same as they were when the datareader loaded them on the page load event. How can I submit the values that the user updates, not what is already there from page load.
Code:
Public Property vehicleid As Integer
Public Property connstring As String = "myconnectionstring..."
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
vehicleid = Integer.Parse(Request.QueryString("vehicID"))
Dim svEnterdate, stocknum, make, model, color As String
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "select * from vehicle where vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
conn.Open()
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
svEnterdate = dr("enterdate").ToString()
stocknum = dr("stock_num").ToString()
make = dr("make").ToString()
model = dr("model").ToString()
color = dr("color").ToString()
End While
conn.Close()
EnterDateTXT.Text = svEnterdate
StockNumTXT.Text = stocknum
MakeTxt.Text = make
ModelTXT.Text = model
ColorTxt.Text = color
End Sub
'inbetween these 2 events the user can manipulate all the controls .text values, yet the
' .text values of the submitted controls below are the same as the ones filled by the
'datareader
Protected Sub SubmitBTN_Click(ByVal sender As Object, ByVal e As EventArgs) Handles SubmitBTN.Click
Dim conn As New OleDbConnection(connstring)
Dim sql As String = "UPDATE Vehicle" & _
" SET stock_num=#stock, make=#make, model=#model, color=#color, enterdate=#enter " & _
"WHERE vehicleid=#vid"
Dim cmd As New OleDbCommand(sql, conn)
cmd.Parameters.AddWithValue("#vid", vehicleid)
cmd.Parameters.AddWithValue("#stock", StockNumTXT.Text)
cmd.Parameters.AddWithValue("#make", MakeTxt.Text)
cmd.Parameters.AddWithValue("#model", ModelTXT.Text)
cmd.Parameters.AddWithValue("#color", ColorTxt.Text)
cmd.Parameters.AddWithValue("#enter", EnterDateTXT.Text)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub

In your page load code, Check For Post back
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
' Write your code to read data from database here
End
End Sub
If you dont check for postback in your page load event, Everytime when you click the submit button, It is going to excute the code in your page load ( load the content again to the text box) first. So whatever you entered in the textbox will be overwritten by the content form the database and that will be saved back again to the database.
To undestand this. Put a breakpoint in your Page_load event code and another in your button click event code. Now enter some value in textbox and click the button and see whether your code block in pageload is executing or not.
Checking the Postback check in your page_load will fix the problem.
http://msdn.microsoft.com/en-us/library/system.web.ui.page.ispostback.aspx

Related

ASP VB Stuck on Dynamic Controls, Viewstate, and Postback. Could really use some help to get back on track

I've been reading posts and articles and just getting a little confused and consequently burning through time I don't have at the moment
Can someone look at my code and tell me where I've gone wrong?
Partial Class PayerContacts
Inherits System.Web.UI.Page
Dim connStrDRContacts As String = ConfigurationManager.ConnectionStrings("DRContacts_SQL").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
navBuild()
End Sub
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack Then
LoadContacts(ViewState("objSender"))
End If
End Sub
Private Function navBuild() As Integer
Dim SQLstrDRs As String = "SELECT * FROM DRList"
Dim DbConnDRs As SqlConnection = New SqlConnection(connStrDRContacts)
DbConnDRs.Open()
Dim dtDRsTemp As New DataTable
Dim SQLAdapterDRs As New SqlDataAdapter(SQLstrDRs, DbConnDRs)
SQLAdapterDRs.Fill(dtDRsTemp)
'Loop through each row of the DataView to create HTML table data
Dim NewTableRow As New TableRow
For Each row As DataRow In dtDRsTemp.Rows
'CREATE table with button to display contacts related to client (one to many)
Dim NewTableButton As LinkButton = New LinkButton
NewTableButton.ID = "btnDRName" & NewTableText
NewTableButton.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler NewTableButton.Click, AddressOf LoadContacts
Next
Return 0
End Function
Protected Sub LoadContacts(sender As Object, e As EventArgs)
Dim LoopCount As Integer = 0
Dim SQLstrLoadTable As String = "SELECT * FROM ContactList WHERE DRVendor = '" & sender.Text.ToString & "'"
and so on....
SQLAdapterLoadTable.Fill(dtLoadTableTemp)
Dim NewTableRow As New TableRow
For Each row As DataRow In dtLoadTableTemp.Rows
'CREATE Accordion to display data
NewAccordion.ID = "ContactAccordion" & LoopCount
NewAccordion.Visible = True
blah, blah...
'SET Pane
NewAccordionPane.HeaderContainer.ID = "PaneHeader" & LoopCount
NewAccordionPane.ContentContainer.ID = "PaneContent" & LoopCount
'CREATE button to open ModalPopup to EDIT each record
Dim imgGear As New ImageButton
imgGear.ID = "btnGear" & row!ID.ToString
imgGear.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler imgGear.Click, AddressOf EditRecord
'LOAD Pane
NewAccordionPane.HeaderContainer.Controls.Add(NewHeaderTable)
NewAccordionPane.ContentContainer.Controls.Add(New LiteralControl(NewTableText))
ViewState("objSender") = sender
End Sub
Protected Sub EditRecord(ByVal sender As Object, ByVal e As EventArgs)
'Open ModalPopup to edit record
popup.Show()
pnlAddEdit.Visible = True
End Sub
End Class
The Infinities Loop articles on ViewState and Dynamic Controls should really be read by every Webforms developer: -
http://mocha.mojoskins.com/SharedFiles/Download.aspx?pageid=566&mid=786&fileid=38
http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_
The examples are in C# but you should be able to figure out what's going on, it's the same base class library after all.

Visual Basic ASP.NET Not Reading Unchecked Checkbox Properly

I have a web application that reads from a SQL database to create a gridview. From this gridview I want to select some data and transfer it back to another page via session variable. I have tried to create continuity by checking the boxes previously selected, but if I uncheck them and send the information back, the unchecked box remains in the session variable data.
This is the code that checks the session variable and checks boxes accordingly.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim String1 As String = ""
Dim String2 As String = ""
Dim boolcheck As Boolean = False
For Each row As DataRow In employeelist.Rows
String1 = row.Item(0)
For Each row2 As GridViewRow In EmployeeListGridView.Rows
String2 = row2.Cells(1).Text
If String1 = String2 Then
Dim checkRow As CheckBox = TryCast(row2.Cells(0).FindControl("checkRow"), CheckBox)
checkRow.Checked = True
End If
Next
Next
End Sub
This is the code that stores a datatable to the session variable
Protected Sub SelectButton_Click(sender As Object, e As EventArgs) Handles SelectButton.Click
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn() {New DataColumn("ZID"), New DataColumn("Last Name")})
For Each row As GridViewRow In EmployeeListGridView.Rows
If row.RowType = DataControlRowType.DataRow Then
Dim checkRow As CheckBox = TryCast(row.Cells(0).FindControl("checkRow"), CheckBox)
If checkRow.Checked Then
Dim zid As String = row.Cells(1).Text
Dim lastname As String = row.Cells(3).Text
dt.Rows.Add(zid, lastname)
End If
End If
Next
Session("employeedt") = dt
Response.Redirect("ManagerTraining.aspx")
End Sub
If a box is checked on page load from the first bit of code, unchecked by the user, the second piece of code will step into the "If checkRow.checked" statement even though the user has unchecked that box. The checkboxes are contained in a gridview. I am using ASP.NET and VB. I feel like the changes aren't being committed if the user unchecks.
Please read about the ASP.NET lifecycle.
Page.Load always executes before the event handlers on postback. You should wrap the code setting the checkbox values in
If not isPostback Then
Dim checkRow As CheckBox = TryCast(row2.Cells(0).FindControl("checkRow"), CheckBox)
checkRow.Checked = True
End If

Asp.net Label not updated after postbck. Need extra refresh

I'm inserting record into the DB after the button has been clicked then on page load I'm checking if the user attended today and display the right label. Problem is it keeps displaying the wrong label after postback, but if I do one refresh i get the correct label displayed.
Protected Sub AttendBtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles AttendBtn.Click
Dim con As New SqlConnection
Dim conString As String
conString = ConfigurationManager.ConnectionStrings("attConnection").ConnectionString
con = New SqlConnection(conString)
con.Open()
Dim cmd As New SqlCommand("INSERT INTO Attendance (UserID, Date, Attendance_Cycle, Comments)VALUES (#UserID, #Date, #Attendance_Cycle, #Comments)", con)
cmd.Parameters.AddWithValue("#Date", DateTime.Now)
cmd.Parameters.AddWithValue("#Attendance_Cycle", GlobalVarAndFunc.CurrentCycle(2))
cmd.Parameters.AddWithValue("#Comments", "")
cmd.Parameters.AddWithValue("#UserID", GlobalVarAndFunc.UserID)
cmd.ExecuteNonQuery()
con.Close()
End Sub
and on page load
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If GlobalVarAndFunc.HasAttended Then
attend_LB.Text = "You already attended today"
Else
attend_LB.Text = "Attend now"
End If
End Sub
GlobalVarAndFunc.HasAttended function checks if the User has pressed on the attended button today or not
Please understand the flow of asp page. System will execute your page load before the button click event. So in your case, the moment page_load was called at that time you get the value that is already there in DB because system hasn't executed click event yet. When click event gets execute then your value gets into DB (before this event your DB wasn't updated). So on next refresh you gets the correct value.
Solution : Place page_load code in btn_click event to get the result in one go.

asp.net update with datareader don't work

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

Value in textbox is always the same on update statement

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

Resources