currently I am working on a project named online exam.
All the controls are dynamically created.
I have a webpage where I want to display the student details.
I displayed those details correctly in a table.
Now here comes the time to edit those details.
To edit a record I use the linked button named edit.
When a user clicks on that Linked button the data in that row is replaced with new textboxes.
Upto here I am OK.
Now when I click on the save changes button after making changes to the textboxes.
The old values are not replaced by the new values and the old values remains.
The code for creating textboxes in the table is as follows :
Public Sub Edit_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For x As Integer = 0 To EditList.Count - 1
If sender.id.substring(4) = EditList(x).ID.Substring(4) Then
Session("PreviousRollNo") = RollNoList(x).Text
Dim txtName As New TextBox
txtName.Text = NameList(x).Text
NameList(x).Text = ""
NameList(x).Parent.Controls.Add(txtName)
txtList.Add(txtName)
Dim txtCourse As New TextBox
txtCourse.Text = CourseList(x).Text
CourseList(x).Text = ""
CourseList(x).Parent.Controls.Add(txtCourse)
txtList.Add(txtCourse)
Dim txtAdmissionDate As New TextBox
txtAdmissionDate.Text = AdmissionList(x).Text
AdmissionList(x).Text = ""
AdmissionList(x).Parent.Controls.Add(txtAdmissionDate)
txtList.Add(txtAdmissionDate)
Dim btnSaveChanges As New Button
btnSaveChanges.Text = "Save Changes"
EditList(x).Text = ""
EditList(x).Parent.Controls.Add(btnSaveChanges)
AddHandler btnSaveChanges.Click, AddressOf btnSaveChanges_Click
Session("EditButtonClicked") = True
Dim btnCancel As New Button
btnCancel.Text = "Cancel"
DeleteList(x).Text = ""
DeleteList(x).Parent.Controls.Add(btnCancel)
AddHandler btnCancel.Click, AddressOf btnCancel_Click
Session("CancelButtonClicked") = True
txtName.Focus()
Exit For
End If
Next
End Sub
The code for Save Changes button is as follows :
Public Sub btnSaveChanges_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If txtList(0).Text = "" Then
Dim trError As TableRow = New TableRow
Dim tdError As TableCell = New TableCell
tdError.ColumnSpan = 7
Dim lblError As New Label
lblError.Text = "Please enter name of the student."
lblError.ForeColor = Drawing.Color.Red
tdError.Controls.Add(lblError)
trError.Controls.Add(tdError)
tbl.Controls.Add(trError)
ElseIf txtList(1).Text = "" Then
Dim trError As TableRow = New TableRow
Dim tdError As TableCell = New TableCell
tdError.ColumnSpan = 7
Dim lblError As New Label
lblError.Text = "Please enter the course."
lblError.ForeColor = Drawing.Color.Red
tdError.Controls.Add(lblError)
trError.Controls.Add(tdError)
tbl.Controls.Add(trError)
ElseIf txtList(2).Text = "" Then
Dim trError As TableRow = New TableRow
Dim tdError As TableCell = New TableCell
tdError.ColumnSpan = 7
Dim lblError As New Label
lblError.Text = "Please enter the Admission Date"
lblError.ForeColor = Drawing.Color.Red
tdError.Controls.Add(lblError)
trError.Controls.Add(tdError)
tbl.Controls.Add(trError)
Else
Dim cb As New OleDbCommandBuilder(da)
Dim editRow() As DataRow
editRow = ds.Tables("Student_Detail").Select("Roll_No = '" & Session("PreviousRollNo") & "'")
editRow(0)("Name") = txtList(0).Text
editRow(0)("Course") = txtList(1).Text
editRow(0)("Admission_Date") = txtList(2).Text
da.Update(ds, "Student_Detail")
Page.Response.Redirect("ChangeUserDetails.aspx")
End If
End Sub
I get the error sying that array is out of the bounds. on the first line of the btnSaveChanges_Click.
It means txtlist is always cleared when I click on Save Changes Button.
So I stored txtList in a Session like Session("txtList") = txtList.
and retrieved the data from that. But now I get the old values of the textbox instead of the newer ones.
Here txtList is a list (of Textbox)
Firstly, welcome to the ASP.NET WebForms Page Life Cycle. Remember its pattern with the simple mnemonic: SILVER = Start, Init, Load, Validate, Events, Render.
Secondly, HTTP is stateless. WebForms does an amazing job of hiding this fact from you using ViewState until you do something a little out of the ordinary (as you're now attempting), and it all appears to fall apart. What's really happening is that you're starting to see side-effects of how WebForms is managed, and how it's not as much like WinForms (or another stateful system) as you might think.
When you're responding to an event server-side in WebForms, it's easy to get the impression that nothing has changed. That the entire page is as you left it "last time". All the controls are there, the values you may have set programatically are still set. Magic. Not magic. What's actually happened is the entire page has been re-constructed to respond to that event. How was it re-constructed? By a combination of your page definition (markup), actions taken in control event handlers, and the form data posted back by the client.
Confusing? OK, let's consider an example. Say you've got a page with two controls on it. A textbox named txtInput and a button named btnSubmit with event handler btnSubmit_Click. When the user first requests the page, the HTML for these controls is derived from your markup (aspx page) and returned to the client. Next, the user sets a value in txtInput and clicks the submit button. The server then re-creates the page from scratch based on your markup. At this early stage of the life-cycle, the controls still have their default values. We then hit the Load stage of the life-cycle, and "if the current request is a postback, control properties are loaded with information recovered from view state and control state." In other words, by the time the life-cycle gets to Init, the control has been created from markup, but still has its default value. The Load stage then sets the value according to Postback data.
Left wondering how this applies to your scenario? You're adding your dynamic controls in response to a control event. There's two things wrong with that:
It's too late in the page life-cycle for Init to set the values based on data posted back from the client (recall SILVER, Event is after Init).
Your button click event handler is only run once, in response to the postback where the user clicked the button. But remember on each postback the page is entirely re-created. So the dynamic controls no longer exist as far as the server is concerned! You'll notice that not only are the controls not present server side when responding to the submit event, but after the page has handled it, they're no longer present client-side either.
So what's the answer? Well the "Life-Cycle Events" section of the page I linked offers a clue. It states that the PreInit event be used to (among other things) "Create or re-create dynamic controls". Why would we do it in PreInit? So it's early enough in the page life-cycle for the later events to properly handle it (like setting the values posted back from the client).
Now, I know, you want to add the controls based on the user clicking on the button. How does that fit? The trick is that you've got to manage the "state" yourself. Huh? the state? By this I mean MyDynamicControlsShouldBeShown = true / false. When the button is clicked, creating the controls in response to the button-click event handler is the right action (there's not really any choice there). But you need to store that state somehow so you know on subsequent requests to the page, whether those controls should be re-created in PreInit. One neat option would be to check for the ID of your dynamic control in Request.Form.Keys. If the control ID is present in the Keys collection, then the user is posting back a value for the control, so you should re-create it.
A side-note on the use of Session
Hopefully based on the above you've realised why putting the controls into Session didn't work. But to be clear, the controls you put into the Session object were no longer part of a page that existed (remember, the page gets completely re-created for each request. Those controls were no longer hooked up to the Page events, so didn't get their values populated between Page Init and Load. If somehow it did work, it still wouldn't be a particularly good idea, as Session is not per-request. So what would happen if a user had the same page open in multiple tabs? Strange things, that's what.
Related
I had a situation where I was dynamically creating LinkButtons basically with no properties set on PageInit, and then later on adding the properties about those LinkButtons on another separate button's click event.(i.e. text, adding a click eventhandler, etc).
The problem was, I had to click the LinkButton twice for the click event handler to fire. Bear in mind, all of this is inside an update panel.
After looking at it up and down, I realized I was setting the ID for it to the same thing twice (on PageInit and also when I later set the properties). I saw that and figured it would muck up things in the control hierarchy and I understand it was the problem...but what I don't fully understand is the why.
Can someone explain to me what the technical cause was for having to click the LinkButton twice and why setting the ID to same thing twice caused this?
CODE
This occurs on CreateChildControls()
Private Sub InitializeLinkBreadCrumbPlaceHolders()
Dim counter As Integer = 0
'Adding the handlers has to take place before/on Page.Init...
For counter = 0 To LEVEL_CAP
_linkDynamic = New LinkButton()
'Add all the links
Me._placeHolder.Controls.Add(_linkDynamic)
With _linkDynamic
AddHandler .Click, AddressOf Link_Click
.Style.Add("display", "none")
.ID = String.Format("lbl{0}", counter)
End With
Next
End Sub
And this occurs when a regular button is pressed (keep in mind all of this is inside an update panel)
Private Sub SetHyperLinkBreadCrumbValues(Optional ByVal ShouldAddAsLink As Boolean = True)
'Don't add a new link if we went backwards
If ShouldAddAsLink Then
Me.Links(Me.CurrentLevel) = Me.LinkHeader
End If
'Go through the collection to set the values of the existing linkbuttons
For Each element As DictionaryEntry In Me.Links
'Links 1-based index
With CType(Me._placeHolder.Controls.Item(CInt(element.Key) - 1), LinkButton)
.Font.Name = "Arial"
.Font.Size = 11
If CInt(element.Key) > 1 Then
.Text = String.Format(" > {0}", CStr(element.Value))
Else
.Text = CStr(element.Value)
End If
.Visible = True
.Style.Add("display", "inline")
End With
Me.TrimDescriptionLink(CType(Me._placeHolder.Controls.Item(CInt(element.Key) - 1), LinkButton))
Next
End Sub
I have seen (and even caused) this behavior from time to time. Inevitably you are not always adding the control (or wiring up the OnClick event in PageInit. The first click causes a PostBack and on the second server page life cycle, you add the control during PageInit. On that second time around (and second button click), the event is wired up and fires the correct event. Are you possibly not wiring up the OnClick event every time during PageInit ?
Can you share some code?
I'm trying to allow my users to enter in large lists of data using an ASP.Net GridView control. The affect I'm trying to create is to make the GridView control act like a spreadsheet. The user can freely enter data and tab from column to column and row to row. The user can use a button at the bottom of the page to add rows as needed. There is also a button at the bottom of the form to save as needed.
To do this, I created a DataTable with a bunch of empty rows and bound it to a GridView. The GridView's columns are template columns that contain textboxes. So, when the page opens, it actually looks like a spread sheet. When the user hits the add rows button, I just add another ten rows to the DataTable the GridView is bound to and it works like a charm.
The issue I'm running into is reading the data that the user entered. When the user hits the paging link or the update button, I would like to update the DataTable with the data the user typed in. Here is what I have.
Private Sub UpdateDataTable()
Dim objCatRow As clsCategoriesRow = Session("gvCategoriesRow")
Dim drQuery() As DataRow = Nothing
Dim drRow As DataRow = Nothing
Dim objRow As GridViewRow = Nothing
Dim intRecNo As Integer = 0
Dim txt As TextBox = Nothing
Dim lbl As Label = Nothing
'Loop through all of the rows in the grid view control
For Each objRow In Me.gvCategories.Rows
'Get the label that contains the identity column
lbl = objRow.Cells(GridColumns.Category).FindControl("lblItemRecNo")
intRecNo = lbl.Text
'Update the datarow bound to this grid view row
'First, query the datarow from the data table
drQuery = objCatRow.Table.Select("recno = " & intRecNo)
'Make sure our query returned a row
If Not IsNothing(drQuery) AndAlso drQuery.Count > 0 Then
'Get the value from the textbox in the grid view
txt = objRow.Cells(GridColumns.Category).FindControl("txtItemCategory")
'Upadte the data row with the value the user entered
'THE VALUE IN txt.Text IS EMPTY. HOW CAN I GET THE VALUE THE USER TYPED IN?
drQuery(0)("Category") = txt.Text
'Get the value from the textbox in the grid view
txt = objRow.Cells(GridColumns.SortORder).FindControl("txtItemSortOrder")
'Upadte the data row with the value the user entered
drQuery(0)("sortorder") = txt.Text
End If
Next
End Sub
The issue is that this is not returning what the user typed in. The line
txt = objRow.Cells(GridColumns.Category).FindControl("txtItemCategory")
returns a reference to the textbox in the templated column. But, it contains the previous value, the value from the view state, not the value the user typed in.
How can I get the value the user typed into the grid?
I want to mention that I know how to add EDIT and UPDATE buttons to each row. I would like to avoid doing that way if I can. My users have huge lists of data to enter in and that approach would make the application unusable.
Thanks in advance,
Mike
The form data posted by the user is found in the Page.Request.Form.Item collection. The Page.Request.Form.AllKeys lists the "keys" associated with all of the form item values.
If Page.Request.Form.HasKeys Then
For Each key as String In Page.Request.Form.AllKeys
' step through the keys and use Page.Request.Form.Item(key) to get the data entered
Next
end If
After testing, I was able to get the data from the Request.Form data or the GridView control during page.load on postback, as long as you don't bind the control on postback, but only during the initial request ("GET").
Keep in mind, controls have to be re-created for each request to the page. The Request data posted is used by ASP.NET to repopulate form data controls only after the controls are re-created on the page and the ViewState for the controls is processed, etc.
Request.Form collection
ASP.NET Page Life Cycle
You should replace this:
txt = objRow.Cells(GridColumns.Category).FindControl("txtItemCategory")
with this
txt = objRow.Cells(GridColumns.Category).FindControl("txtItemCategory").Value
I have a CreateUserWizard control using forms authentication on my login/create user page. I customized the CreateUserWizardStep1 so that I could add some additional validators.
After successfully creating a user with the control and it displays "Complete
Your account has been successfully created." I have added an additional button that will allow the person to create another user by setting the ActiveStepIndex = 0. The problem is, while it sets the ActiveStepIndex correctly, it retains the old user account credentials. I try to clear them manually using the following code, but they still stick...Anyone have any ideas?
Protected Sub btnCreateAnotherUser_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Me.cuwMain.ActiveStepIndex = 0
CleanCreateNewUserInput()
End Sub
Private Sub CleanCreateNewUserInput()
Dim txtUserName As TextBox
txtUserName = FindControlIterative(Me.cuwMain, "UserName")
txtUserName.Text = String.Empty
Dim txtPassword As TextBox
txtPassword = FindControlIterative(Me.cuwMain, "Password")
txtPassword.Text = String.Empty
Dim txtConfirmPassword As TextBox
txtConfirmPassword = FindControlIterative(Me.cuwMain, "ConfirmPassword")
txtConfirmPassword.Text = String.Empty
Dim txtEmail As TextBox
txtEmail = FindControlIterative(Me.cuwMain, "Email")
txtEmail.Text = String.Empty
Dim txtQuestion As TextBox
txtQuestion = FindControlIterative(Me.cuwMain, "Question")
txtQuestion.Text = String.Empty
Dim txtAnswer As TextBox
txtAnswer = FindControlIterative(Me.cuwMain, "Answer")
txtAnswer.Text = String.Empty
End Sub
It finds the textboxes correctly, but it does not actually reset their values, even though in the debugger it says it did.
Thoughts ?
What happens if you call Response.Redirect(Request.Url.ToString(), true)? That should clear everything for you.
Also, the recursive nature of the FindControlIterative call would make your code quite expensive to run as it has to drill down into the control heirarchy for every control that you are looking for.
The problem with your code is that:
In a Wizard control, ViewState is not responsible for storing the modified values for controls such as TextBoxes. These controls implement the IPostBackDataHandler interface. The LoadPostBackData event fires in the page lifecycle, in which the VALUES of the controls load from the form HTTP POST headers... which are resubmitted by the client...
So how to destroy the HTTP POST Headers to clear the control values?
A new request results in new HTTP POST Headers... simply do this in the Button click event handler:
Response.Redirect(Page.Request.Url.ToString());
This has the added benefit that it goes to Step 1 of the wizard so you also dont have to do... wiz.MoveTo(wiz.WizardSteps[0]).
Credit to Konrad - ASP.Net Wizard - How to clear contents of web controls
I feel silly posting this..., but I just turned viewstate off on the CreateUserWizard control and that did it.
Thanks for the help Daniel, I now have a better understanding on how ASP.NET stores information.
How may one get information that was used to programatically generate asp controls?
For example, I pulled a DataTable of user objects from the database and have organized them on a page, listing groupings such as a list of employees directly under the employer for each employer. On the page, I list each user's Username as a LinkButton. When I click one of these employees, I want to redirect the page (which is easy) and set a session variable to the selected user's UserId (which seems not so easy). How can I pull this UserId value back? These elements are not hard-coded with nice names (as they are generated in a for each loop).
Code from comment below:
Dim lnkbtnPm As New LinkButton ' is my link button. '
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
panelToAddControlTo.Controls.Add(lnkbtnPm)
Thanks :)
I think this is what you would use the CommandName and CommandArgument properties of the LinkButton for. Assign the user id as CommandArgument and a suitable string as CommandName and hook up the Command event to an event handler:
Sub LinkButton_Command(sender As Object, e As CommandEventArgs)
' e.CommandArgument will contain the user id '
End Sub
Update
The problem is that the event handler is never attached. Use AddHandler to do that:
Dim lnkbtnPm As New LinkButton
lnkbtnPm.Text = pmDr.Item("Username") ' where pmDr is my datarow. '
lnkbtnPm.CommandArgument = pmDr.Item("UserId")
lnkbtnPm.CommandName = "CommandNameHere"
AddHandler lnkbtnPm.Command, AddressOf LinkButton_Command
panelToAddControlTo.Controls.Add(lnkbtnPm)
I'm sure this question has been asked a million times, however I haven't been able to find an answer that solves my problem.
I am programmatically adding some custom user controls to a PlaceHolder which I have on a simple aspx page. All of the user controls Postback's work correctly except for one which has a Gridview on it.
For some reason any postback that gets fired from within this control, does not call the specified event on the first click, however all future clicks it will work fine. I have no idea why this is the case, but many solutions I have found, suggest adding an ID to the ascx User Control, however this doesn't work in my case.
I've taken a look at the source file for the page that gets generated before and after the first click, javascript used for calling the postback changes, i.e
Before first click: onclick="javascript:__doPostBack('tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
After first click: onclick="javascript:__doPostBack('OFFHome1$tmpControlID$sgvPrimaryEmploymentHistory','Select$0')"
OFFHome1 is the parent user control which exists on the aspx page. All other controls are added to a placeholder in this control, i.e.
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="OFFHome.ascx.vb" Inherits="UmbracoUserControls.OFFHome" %>
<asp:PlaceHolder ID="phOFFSection" runat="server"></asp:PlaceHolder>
Nothing to complicated. Then in the code behind the controls are loaded into the placeholder using the following:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim StepCompleted As Boolean = .FillControl()
If StepCompleted Then
Exit Sub
End If
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
End If
End Sub
Again, nothing overly complicated. The USERCONTROLNAME is just a const with the value "tmpControlID" in it.
The control that is giving me trouble is a little complicated, I was originally using a custom GridView control that we have created, but have removed it and replaced it with the standard asp one to see if the problem still occurs, and it does.
Any button, on control which fires off a postback will fail the first time, and all future click will work correctly. On the first click the Page_Load event will get called, but that is it.
What am I doing wrong??
After far too much time spent on this, I have finally worked it out.
It was to do with the order of events, however just not where I had thought. The FillControl function was getting called before User Control had been added to the PlaceHolder. I changed this so that it gets called after the User Control was added to the PlaceHolder and now it works first time.
Basically the code looks like this now:
Private Sub LoadNextOFFStep()
Dim ControlName As String = "TestControl.ascx"
phOFFSection.Controls.Clear()
If ControlName IsNot Nothing AndAlso ControlName <> String.Empty Then
Dim NewControl As Object = LoadControl(ControlName)
With NewControl
.ID = USERCONTROLNAME
Dim AllowSkip As Boolean = .AllowSkip()
btnSkip.Visible = AllowSkip
End With
phOFFSection.Controls.Add(NewControl)
Dim StepCompleted As Boolean = CType(phOFFSection.Controls(0), Object).FillControl()
If StepCompleted Then
LoadNextOFFStep()
Exit Sub
End If
End If
End Sub
Thanks for everyone's help.
Well... the answer to the first question is simple: It fails the first time because the ID of the control (or rather, in the postback script) is different on subsequent page loads. It works on subsequent clicks because the control ID stays the same.
Now as to WHY that is... much tougher! But probably something to do with the order of operations here.
Try explicitly setting the NamingContainer value for NewControl:
With NewControl
.NamingContainer = OffHomeOne; // whatever
.ID = USERCONTROLNAME