ASP.NET get hidden value from list view on ItemCommand - asp.net

I have LinkButton and HiddenField in a list view. I want to get the hidden value from HiddenField, so I can store it in Session and when a LinkButton is clicked it transfer the hidden value ( stored in Session) to another page. But I get this error message "Object reference not set to an instance of an object." Here's the function:
Protected Sub lvTimeSheet_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles lvTimeSheet.ItemCommand
Dim id As HiddenField = TryCast(e.Item.FindControl("hfTimeSheetId"), HiddenField)
Dim myId As String = id.Value.ToString
Session("myId") = myId
Server.Transfer("Destination.aspx")
End Sub
The mark-up
</asp:LinkButton><asp:HiddenField ID="hfTimeSheetId1" runat="server" Value='<%# Eval("hfTimeSheetId") %>' />
Every time the LinkButton is clicked, it causes error with above error message. Thank you for any input.

My guess would be that the FindControl isn't finding the hfTimeSheetId control within the row. Do you have it designated as a managed control (i.e. runat="server")?
Also, it might help if you provided the ASPX code to see how you're defining the controls.

The FindControl is returning null, hense the exception. Try changing it to:
Dim id As HiddenField = TryCast(e.Item.FindControl("hfTimeSheetId1"), HiddenField)

Related

Cannot update asp:RangeValidator contained in ListView EditItemTemplate

I am struggling to get an asp:RangeValidator to change the minimum and maximum value programmatically. Unfortunately I am seeing a console error message stating:
'Uncaught Sys.WebForms.PageRequestManagerServerErrorException: Sys.WebForms.PageRequestManagerServerErrorException: The value '' of the MaximumValue property of 'rvDateFrom' cannot be converted to type 'Date'.
My code can be seen below. The calendar is contained in the EditItemTemplate of a ListView, which is contained in an UpdatePanel.
<ewc:CalendarPopup ID="cpDateFrom" runat="server" SelectedDate='<%# Bind("DateFrom")%>' CssClass="date"></ewc:CalendarPopup>
<asp:RangeValidator ID="rvDateFrom" runat="server" ControlToValidate="cpDateFrom" Type="Date" ErrorMessage="Invalid"></asp:RangeValidator>
The code behind is as follows:
Private Sub lvRangeValidatorTest_ItemEditing(sender As Object, e As ListViewEditEventArgs) Handles lvRangeValidator.ItemEditing
lvRangeValidator.EditIndex = e.NewEditIndex
DataBind()
Dim rvDateFrom As RangeValidator = CType(lvRangeValidatorTest.Items(e.NewEditIndex).FindControl("rvDateFrom"), RangeValidator
rvDateFrom.MinimumValue = "01/01/1900"
rvDateFrom.MaximumValue = "01/01/2020"
End Sub
The RangeValidator is found, as intentionally entering the incorrect name throws an instance of an object error, but it does not seem to actually update the RangeValidator. Thus leaving the minimum and maximum values blank.
Thoughts?
Many thanks.
After some more research and unsuccessfully trying to use the ItemDataBound event, I successfully used the DataBound event.
lvRangeValidatorTest_DataBound(sender As Object, e As EventArgs) Handles lvRangeValidatorTest.DataBound
If lvRangeValidatorTest.EditItem IsNot Nothing Then
Dim rvDateFrom As RangeValidator = CType(lvRangeValidator.EditItem.FindControl("rvDateFrom"), RangeValidator)
rvDateFrom.MinimumValue = "01/01/1900"
rvDateFrom.MaximumValue = "01/01/2020"
End If
End Sub

session variable loses value after detailsview new cancel event

I have 3 controls on my web page, a dropdownlist, a detailsview, and a listview.
the dropdownlist controls the record to be displayed on the detailsview and the listview.
when the detailsview enters "new" mode I clear the items of the detailsview and clear the values of the dropdownlist:
If e.CommandName = "New" Then
lvRecipeSteps.Items.Clear()
ddRecipeItemNumber.Items.Clear()
End If
this shows the page with no items on the dropdownlist, the detailsview and listview on new/insert mode.
the issue happens when I click the cancel event, then this code is executed
If e.CommandName = "Cancel" Then
ddRecipeItemNumber.DataBind()
ddRecipeItemNumber.SelectedValue = Session("Id").ToString()
End If
the session variable Id gets assign on page load
Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Session("Id") = ddRecipeItemNumber.SelectedValue
I get an error: "not set to an instance of an object" pointing to: ddRecipeItemNumber.SelectedValue = Session("Id").ToString()
I want to be able to save the record Id, that is on the dropdown before the new/insert event begins, and then if the event gets cancelled, set the controls back to the record that were displaying before the insert/new action started.
I read that using sessions variables is a good way of doing this, but I most be doing something wrong that when the event cancel is executed, the values is then lost.
Please let me know if I can get some help finding a solution for my problem.
Thank you very much.
place the Session("Id") = ddRecipeItemNumber.SelectedValue inside the condition below:
if (!IsPostBack)
{
Session("Id") = ddRecipeItemNumber.SelectedValue;
}
just need to convert it to VB
UPDATE 1
If your code is not inside a Data control then you could allocate its selected value like the code below:
on your aspx form:
<asp:DropDownList ID="DropDownList2" runat="server"
OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged"
AutoPostBack="true" ></asp:DropDownList>
on your code behind:
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Id"] = DropDownList2.SelectedItem.Value;
}
UPDATE 2
also if you want to change the selected value on your code this would be the right code to do:
instead of this line ddRecipeItemNumber.SelectedValue = Session("Id").ToString()
use this one
ddRecipeItemNumber.Items.FindByValue(Session("Id").ToString()).Selected = true;

Listview - Capture text from dynamically created textbox on Update

I have a database and a bound Listview with dynamically created controls. I have been attempting to find a way to capture the new value using markup as
<asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" DataKeyNames="ID" OnItemUpdating="ListView1_ItemUpdating">
and code behind as
Protected Sub ListView1_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles ListView1.ItemUpdating
Dim capString As String = String.Empty
capString = e.NewValues
End Sub
This fails with the error Unable to cast object of type 'System.Collections.Specialized.OrderedDictionary' to type 'System.String'
I'm hoping someone could help me identify either a better way to accomplish capturing this data, or if it is possible to cast this data and how to do it in code.
Try
Dim capString As String = String.Empty
capString = e.NewValues(1) As String
Substitute 1 with an appropriate index for your capString.

SelectedIndex add controls

Based on a choice of "Other" in a dropdown I want to add a label and textbox to a <p> tag. I have added runat=server in the <p> tag.
Protected Sub deptDdl_SelectedIndexChanged(sender As Object, e As System.EventArgs) Handles deptDdl.SelectedIndexChanged
'If the user chooses other for the department type add
'a label and textbox to allow them to fill in a department not listed
If deptDdl.SelectedValue.ToString = "Other" Then
Dim deptLbl As Label = New Label
deptLbl.Text = "Enter the Department Name"
Dim deptTb As TextBox = New TextBox
deptTb.MaxLength = 20
Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(2, deptLbl)
Page.FindControl("m_ContentPlaceHolder1_deptPtag").Controls.AddAt(3, deptTb)
End If
End Sub
I keep getting an unhandled exception stating Object reference not set to an instance of an object.
What am I missing?
If your <p>-tag is runat=server you should be able to reference it in the codebehind -file directly. Give it an ID deptPtag, then this should be autogenerated in the designer.vb-file:
Protected WithEvents deptPtag As Global.System.Web.UI.HtmlControls.HtmlGenericControl
But you also have to ensure that your dynamic controls are recreated on every postback(latest in Page_Load, events are too late for reloading the ViewState). Otherwise you won't be able to read deptTb.Text or handle it's TextChanged-event.
The ID must be the same on every postback to correctly load the ViewState.
My answer on this question explains your NullReferenceException.
It's a special behaviour of FindControl from within a MasterPage's content-page.

How to get textbox value from one aspx pageto another in Asp.Net

I have two aspx pages the first page has a textbox and the second aspx page has one textbox
In the second Page I am giving value to the text box by generating a session and giving that session ID to the textbox on the samepage
Now I need to retrieve back that session ID from the textbox and display it in first aspx page textbox which is not happening and not getting any error.
Here is my code for the first aspx page:
<asp:TextBox ID="CopySession" runat="server"></asp:TextBox>
This is my code for displaying the retrieved Session ID:
If IsPostBack Then
Dim text1 As TextBox = Me.PreviousPage.FindControl("SessionValue")
CopySession.Text = text1.Text
End If
This is my second aspx page:
<asp:TextBox ID="SessionValue" runat="server"></asp:TextBox>
This is my code behind for second aspx page:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Session("ID") Is Nothing Then
Session("ID") = Guid.NewGuid.ToString
SessionValue.Text = Session("ID")
End If
End Sub
Its quite simple just type cast it with previous page like following
(Me.PreviousPage as yourPageClass).SessionValue.Text
or use this on first page
<%# PreviousPageType VirtualPath="~/SecondPage.aspx" %>
and better way is
internal function TextBoxText() as string
return SessionValue.Text
end function
and get it on page one
currentPageTextbox.Text = Page.PrevousPage.TextBoxText
If you put it Session, just retrieve it. On Page_Load of your first page, do:
Dim sessionID As String = TryCast(Session("ID"), String)
If Not String.IsNullOrEmpty(sessionID) Then
SessionValue.Text = sessionID
End If
Am also looking around the same scenario and I found this URL as useful to me.
Am sharing this to you.. Exploring Session in ASP.Net
Refer this too
How can I access Session vars from Base class in ASP.Net?
ASP.Net MVC: How do you access the session from a different project within the solution?

Resources