Shopping Cart Implemented in Visual Studio Express - asp.net

i implemented a shopping cart found here: http://www.beansoftware.com/ASP.NET-Tutorials/Developing-Shopping-Cart.aspx
Whenever I run the project separately it would work perfect but when i move the .aspx classes and items into my project, i get these errors:
Type lstcart is not declared, It may be inaccessible due to its protection level. Place:Cart.aspx.vb line 22
Type CartItem is not defined. line 23 and 26
Handles Clause requires a WithEvents Variable defined in the containing type or one of its base types. line 38
"Lblmassage is not declared. It may be inaccessible due to its protection level. line : 41
The code of the program is found in the link i posted above, would anyone help me fixing my issue?
This is my cart.aspx.vb code:
Partial Class Cart
Inherits System.Web.UI.Page
Private Cart As SortedList
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Cart = GetCart()
If Not IsPostBack Then
Me.DisplayCart()
End If
End Sub
Private Function GetCart() As SortedList
If Session("Cart") Is Nothing Then
Session.Add("Cart", New SortedList)
End If
Return CType(Session("Cart"), SortedList)
End Function
Private Sub DisplayCart()
lstCart.Items.Clear()
Dim CartItem As CartItem
Dim CartEntry As DictionaryEntry
For Each CartEntry In Cart
CartItem = CType(CartEntry.Value, CartItem)
lstCart.Items.Add(CartItem.Display)
Next
End Sub
Protected Sub btnRemove_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRemove.Click
If lstCart.SelectedIndex > -1 And Cart.Count > 0 Then
Cart.RemoveAt(lstCart.SelectedIndex)
Me.DisplayCart()
End If
End Sub
Protected Sub btnEmpty_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnEmpty.Click
Cart.Clear()
lstCart.Items.Clear()
lblMessage.Text = ""
End Sub
Protected Sub btnCheckOut_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCheckOut.Click
lblMessage.Text = "Please Wait Checking out..."
End Sub
End Class
This is my Cart.aspx:
<%# Page Title="Cart" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Cart.aspx.vb" Inherits="EliteHosting.Cart" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Shopping Cart</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<div>
<div style="font-size: xx-large; vertical-align: baseline; width: 614px; color: #ffffff;
direction: ltr; height: 112px; background-color: #660000; text-align: left; font-variant: normal">
<br />
My Web Shop</div><br /><br />
Your shopping cart:<br />
<table style="width: 500px" cellspacing="0"
cellpadding="0" border="0">
<tr>
<td style="width: 286px; height: 153px">
<asp:ListBox ID="lstCart" runat="server"
Width="267px" Height="135px">
</asp:ListBox>
</td>
<td style="height: 153px">
<asp:Button ID="btnRemove" runat="server"
Width="100px" Text="Remove Item" /><br /><br />
<asp:Button ID="btnEmpty" runat="server"
Width="100px" Text="Empty Cart" />
</td>
</tr>
</table>
<br />
<asp:Button ID="btnContinue" runat="server"
PostBackUrl="~/Order.aspx" Text="Continue Shopping" />
<asp:Button ID="btnCheckOut" runat="server" Text="Check Out" /><br />
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

Related

Button on usercontroll doesn't fire / raise event

i have a usercontroll with two buttons and i want to get the raiseevent in the page where i call the usercontrol. Everything works fine except that i can't catch the event when i click the button on the user contol.
my markup for the uc:
<%# Control Language="VB" AutoEventWireup="false" CodeFile="MsgBox.ascx.vb" Inherits="MsgBox" ClassName="MsgBox" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="act" %>
<style type="text/css">
.Modal_trans {
opacity: 0.8;
filter: alpha(opacity=60);
}
</style>
<link rel="stylesheet" type="text/css" href="../Styles/StyleSheet.css" />"
<asp:Panel ID="PopPanel" runat="server"
Width="500px" Height="50px" DefaultButton="ok" Style="overflow:hidden;" CssClass="ModalGrid">
<table style="width: 100%; border-collapse: collapse; border: 0px;">
<tr id="boxheader" runat="server" style="cursor: move;">
<th colspan="2" style="padding-left: 10px; padding-top: 3px; padding-bottom: 3px;">
<asp:Label ID="lblTitle" runat="server" Text="Help"></asp:Label>
</th>
</tr>
<tr>
<td>
<asp:Image ID="Image" runat="server" ImageUrl="../images/info.png" />
</td>
<td style="padding: 10px; width: 220px;">
<div style="width: 295px; height:70px;"">
<asp:Label ID="lblMsg" runat="server" BackColor="#CCCCCC" />
</div>
</td>
</tr>
<tr>
<th colspan="2" style="padding-right: 20px; padding-top: 7px; padding-bottom: 7px;"" >
<asp:LinkButton ID="LinkButton1" runat="server" Style="display:none" ></asp:LinkButton>
<asp:Button ID="ok" runat="server" Text="Ok" Width="80px" />
<asp:Button ID="no" runat="server" Text="No / Cancel" Width="80px" Visible="False" />
</th>
</tr>
</table>
</asp:Panel>
<act:ModalPopupExtender ID="PopUp" runat="server" Enabled="True"
PopupControlID="PopPanel" TargetControlID="LinkButton1" BackgroundCssClass="Modal_trans"
OkControlID="ok" PopupDragHandleControlID="boxheader" Y="0" DropShadow="True">
<Animations>
<OnShown>
<Sequence AnimationTarget="PopPanel">
<Parallel Duration=".5" Fps="25">
<Move Horizontal="-175" Vertical="200" />
<Resize Width="350" Height="142"/>
<FadeIn />
</Parallel>
</Sequence>
</OnShown>
<OnHiding>
<Sequence AnimationTarget="PopPanel">
<%-- Scale the flyout down to 5% to make it disappear --%>
<Parallel Duration=".75" Fps="25">
<Scale ScaleFactor="0.05" Center="true" ScaleFont="true" FontUnit="px" />
<FadeOut />
</Parallel>
<%-- Reset the styles on the info box --%>
<StyleAction Attribute="display" Value="none"/>
<StyleAction Attribute="width" Value="350px"/>
<StyleAction Attribute="height" Value=""/>
<StyleAction Attribute="fontSize" Value="12px"/>
<%-- Re-enable the button --%>
<EnableAction Enabled="true" AnimationTarget="ok" />
</Sequence>
</OnHiding>
</Animations>
</act:ModalPopupExtender>
and the code behind
Partial Class MsgBox
Inherits System.Web.UI.UserControl
Public Shared IconInfo, IconExec, IconQues, IconError As Object
Public Property MsgText As String
Get
Return lblMsg.Text
End Get
Set(ByVal value As String)
lblMsg.Text = value
End Set
End Property
Public Event MsgButtonClick(ByVal buttonName As String)
Protected Sub MsgButtonOKClick(ByVal sender As Object, ByVal e As EventArgs) Handles ok.Click
RaiseEvent MsgButtonClick("ok")
End Sub
Protected Sub MsgButtonDenyClick(ByVal sender As Object, ByVal e As EventArgs) Handles no.Click
RaiseEvent MsgButtonClick("no")
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
IconInfo = "Show Information Icon"
IconExec = "Show Warning Icon"
IconQues = "Show Question Icon"
IconError = "Show Error Icon"
End Sub
Public Sub Pop(Optional ByVal Message As String = "", Optional ByVal Mode As Object = "IconInfo", Optional ByVal Title As String = "Info Message")
no.Visible = False
ok.Text = "Ok"
If Title <> "" Then
lblTitle.Text = Title
End If
Select Case Mode
Case "IconInfo"
Image.ImageUrl = "../images/info.png"
no.Visible = False
ok.Text = "Ok"
lblTitle.Text = "Info"
Case "IconExec"
Image.ImageUrl = "../images/exc.png"
no.Visible = False
ok.Text = "Ok"
lblTitle.Text = "Warning"
Case "IconQues"
Image.ImageUrl = "../images/ques.png"
no.Visible = True
ok.Text = "Yes" lblTitle.Text = "Question"
Case "IconError"
Image.ImageUrl = "../images/error.png"
no.Visible = False
ok.Text = "Ok"
lblTitle.Text = "Error"
End Select
PopUp.Show()
End Sub
Protected Sub No_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles no.Click
PopUp.Hide()
End Sub
Tested also with the variation
Public Event MsgButtonClick As EventHandler
Protected Sub MsgButtonOKClick(ByVal sender As Object, ByVal e As EventArgs) Handles ok.Click
RaiseEvent MsgButtonClick(sender, e)
End Sub
Protected Sub MsgButtonDenyClick(ByVal sender As Object, ByVal e As EventArgs) Handles no.Click
RaiseEvent MsgButtonClick(sender, e)
End Sub
In my page, it's a contetpage of a master page with update panel i try to catch the event with following in the code behind
Protected Sub test() Handles PopMsg.MsgButtonClick
Response.Write("Done")
End Sub
In the markup on the page i have placed the controldirectly behind the ContentTemplate of the UpdatePanel
<msg:PopInfoMsg ID="PopMsg" runat="server" />
And call the UC with a button click
Protected Sub HelpMsg()
PopMsg.MsgText = "My first Test<br/> Cheers<br/>"
PopMsg.Pop("", "IconInfo", "Info")
End Sub
The control open as expected, but when clicking the "OK" button the control close without an event.
In VS i tried to debug at the Button Click but the code doesn't run to this point.
Where i'am wrong? Confusing me the last days...
Cheers, Alex

UserControl inside DataList

I have a UserControl inside DataList, I fill the controls inside the usercontrol according to the PrimeryKey of the DataList's data. At first load program behaves as expected but when user changes page index all the MessageID's returns 0, most probably value coming with
<%# Eval("id").toString()%> is lost. I dont want to hard code the usercontrol because i used it in many place in the project, it makes the code maintainable. How can i correct this behaviour? Thanks in advance.
My code is below:
<asp:DataList ID="DataList1" runat="server" Width="658px">
<ItemTemplate>
<table style="width: 100%;">
<tr>
<td style="font-weight: 700; color: #FF0000; font-size: medium; font-size: 10pt; font-family: Tahoma">
<%# Eval("hadding") +" ["+Eval("startTime")+" - "+Eval("endTime")+"]"%>
</td>
</tr>
<tr>
<td style="font-weight: 700; font-size: 10pt; font-family: Tahoma">
<%# Eval("location") %>
</td>
</tr>
<tr>
<td>
<uc1:MyUserControl ID="MyUserControl1" runat="server" MessageID='<%# Eval("id").toString()%>' />
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<table>
<tr>
<td>
<asp:Button ID="btnfirst" runat="server" Font-Bold="true" Text="<<" Height="31px"
Width="43px" OnClick="btnfirst_Click" /></td>
<td>
<asp:Button ID="btnprevious" runat="server" Font-Bold="true" Text="<" Height="31px"
Width="43px" OnClick="btnprevious_Click" /></td>
<td>
<asp:Button ID="btnnext" runat="server" Font-Bold="true" Text=">" Height="31px"
Width="43px" OnClick="btnnext_Click" /></td>
<td>
<asp:Button ID="btnlast" runat="server" Font-Bold="true" Text=">>" Height="31px"
Width="43px" OnClick="btnlast_Click" /></td>
</tr>
</table>
and my user control:
Partial Class MyUserControl
Inherits System.Web.UI.UserControl
Private _messageID As Integer
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (_messageID > 0) Then
Fill(_messageID)
End If
End Sub
Public Property MessageID As Integer
Get
Return _messageID
End Get
Set(value As Integer)
_messageID = value
End Set
End Property
Protected Sub Fill(messageID As Integer)
'Some code
End Sub
End Class
Difficult to answer without looking at the whole page lifecycle, but you may try to store the MessageId in your control's ViewState, like this :
Public Property MessageID As Integer
Get
If (Me.ViewState("VSMessageID") IsNot Nothing) Then
return CType(Me.ViewState("VSMessageID "), Integer)
else
return 0 // arbitrary value
End Get
Set(value As Integer)
Me.ViewState.Add("VSMessageID", value)
End Set
End Property
Then :
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (MessageID > 0) Then
Fill(MessageID )
End If
End Sub
See http://msdn.microsoft.com/en-us/library/ms227551%28v=vs.85%29.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1
Sorry if bad VB.Net syntax
I solved the problem by changing the usercontrol as such:
Partial Class MyUserControl
Inherits System.Web.UI.UserControl
Public Property MessageID As Integer
Get
Return 0
End Get
Set(value As Integer)
Fill(value)
End Set
End Property
Protected Sub Fill(messageID As Integer)
'Some code
End Sub
End Class
As jbl said, this is because of the page lifecycle. OnPageIndexChange event of an ASPxDataview or on your custom PageIndexChange event for asp.net DataList, code work as such:
DataList (or ASPxDataview ) Load
UserControl Property setting
UserControl Load
PageIndexChange event
UserControl Load
UserControl Property setting
That's why on UserControl.Load Property is not set.

ASP.NET VB add button that has removechild() function

I just want to know how to add a button that has a removechild() or replacechild() function on my XML. Been searching for this for a week now.
Any suggestions would be greatly appreciated. Thanks :)
This is my xml file content
<?xml version="1.0" encoding="utf-8"?>
<theNews>
<news>
<contents>News3 Contents</contents>
<title>News3 Title</title>
<pubDate>February 13, 2012</pubDate>
</news>
<news>
<contents>News2 Contents</contents>
<title>News2 Title</title>
<pubDate>February 1, 2012</pubDate>
</news>
<news>
<contents>News1 Contents</contents>
<title>News1 Title</title>
<pubDate>January 22, 2012</pubDate>
</news>
</theNews>
This is the code for my News Updater
<%# Page Title="" Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="NewsUpdater.aspx.vb" Inherits="NewsUpdater" %>
<%-- Add content controls here --%><asp:Content ID="Content1" runat="server"
contentplaceholderid="ContentPlaceHolder1">
<p>
</p>
<table align="center" style="width: 63%">
<tr>
<td align=center>
<div>
<h3>News Title</h3>
<asp:TextBox runat="server" ID="txtTitle" Width="308px"></asp:TextBox>
<br />
<h3>News Content</h3>
<asp:TextBox runat="server" ID="txtContents" TextMode="MultiLine" Height="119px" Width="513px"></asp:TextBox>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="Update News" />
</div></td>
</tr>
</table>
<p>
<br />
</p>
And this is the code behind the NewsUpdater button
Partial Class NewsUpdater
Inherits System.Web.UI.Page
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xmlFile As New System.Xml.XmlDocument()
xmlFile.Load("D:\My Documents\PresentableII\NewsContent.xml")
Dim theNewsTag As System.Xml.XmlElement = xmlFile.CreateElement("news")
Dim theTitleTag As System.Xml.XmlElement = xmlFile.CreateElement("title")
Dim theContentsTag As System.Xml.XmlElement = xmlFile.CreateElement("contents")
Dim theTitleText As System.Xml.XmlText = xmlFile.CreateTextNode(txtTitle.Text)
Dim theContentsText As System.Xml.XmlText = xmlFile.CreateTextNode(txtContents.Text)
theTitleTag.PrependChild(theTitleText)
theContentsTag.PrependChild(theContentsText)
theNewsTag.PrependChild(theTitleTag)
theNewsTag.PrependChild(theContentsTag)
xmlFile.DocumentElement.PrependChild(theNewsTag)
xmlFile.Save("D:\My Documents\PresentableII\NewsContent.xml")
Response.Redirect("NewsFrame.aspx")
End Sub
I want to add another button that has a function of remove or replace the last/latest entry to the xml.
So would this line do what you want?
xmlFile.DocumentElement.RemoveChild(xmlFile.DocumentElement.LastChild)
xmlFile.DocumentElement.AppendChild(your_replacement_element)

RadListView insertitemtemplate still showing after insert

I have a pretty simple scenario using manual data operations with rad list view. I insert an item into my collection in the ItemInserting event, the listview shows the new item but the insertitemtemplate is still showing. Is my setup wrong? Do I have to manually hide the thing?
Markup
<%# Page Language="VB" AutoEventWireup="false" CodeFile="Test2.aspx.vb" Inherits="Test2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager runat="server" ID="rsm"></telerik:RadScriptManager>
<div>
<telerik:RadListView ID="rlv" runat="server" DataKeyNames="UserID" ItemPlaceholderID="itemPlaceholder" Height="400px" AllowPaging="true">
<InsertItemTemplate>
<tr>
<td>
<div style="vertical-align: middle; white-space: nowrap;">
<asp:LinkButton ID="btnInsert2" runat="server" Text="Insert" CommandName='<%# Telerik.Web.UI.RadListView.PerformInsertCommandName %>'></asp:LinkButton>
<asp:LinkButton ID="btnCancel2" runat="server" Text="Cancel" CommandName='<%# Telerik.Web.UI.RadListView.CancelCommandName %>'></asp:LinkButton>
</div>
</td>
<td>
<div style="vertical-align: middle; white-space: nowrap;">
<telerik:RadComboBox id="RadComboBox1" runat="server" autopostback="True" causesvalidation="False" allowcustomtext="True" backcolor="White" emptymessage="Select a Person" enableloadondemand="True" showmoreresultsbox="True" width="150px" dropdownwidth="200px" zindex="9002" enablescreenboundarydetection="False" style="margin-bottom: 0px" datatextfield="UserName" datavaluefield="pkUserID" filter="Contains" onitemsrequested="RCB_ItemsRequested">
<CollapseAnimation Duration="200" Type="OutQuint" />
</telerik:RadComboBox>
</div>
</td>
</tr>
</InsertItemTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Literal ID="lName" runat="server" Text='<%# Eval("UserName") %>'></asp:Literal>
</td>
</tr>
</ItemTemplate>
<LayoutTemplate>
<asp:LinkButton ID="btnInsert" runat="server" CausesValidation="False" CommandName='<%# Telerik.Web.UI.RadListView.InitInsertCommandName %>' Text="Add User" />
<table>
<tr>
<td style="border: ridge 1px lightgray">
<strong>Applicable Users</strong>
<table>
<asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
</telerik:RadListView>
</div>
</form>
</body>
</html>
Code Behind
Partial Class Test2
Inherits System.Web.UI.Page
Public Property Users As IList(Of UserInfo)
Get
Return If(ViewState("Users"), New List(Of UserInfo))
End Get
Set(ByVal value As IList(Of UserInfo))
ViewState("Users") = value
End Set
End Property
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Me.Users = GetInitialUsers()
End If
rlv.DataSource = Users
rlv.DataBind()
Me.ViewState.SetItemDirty("Users", True)
End Sub
Private Function GetInitialUsers() As IList(Of UserInfo)
Dim Users As New List(Of UserInfo)
Users.Add(New UserInfo(1, "1"))
Users.Add(New UserInfo(2, "2"))
Users.Add(New UserInfo(3, "2"))
Users.Add(New UserInfo(4, "4"))
Return Users
End Function
Protected Sub RCB_ItemsRequested(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadComboBoxItemsRequestedEventArgs)
Dim ComboBox As Telerik.Web.UI.RadComboBox = sender
Dim itemOffset As Integer = e.NumberOfItems
Dim NumberOfItems As Integer = 1000000000
Dim Take As Integer = 20
For i As Integer = 0 To Take
ComboBox.Items.Add(New Telerik.Web.UI.RadComboBoxItem(i + itemOffset, (i + itemOffset).ToString))
Next
Dim NumberOfItemsInComboBox As Integer = e.NumberOfItems + ComboBox.Items.Count
If NumberOfItems > 0 Then
e.Message = [String].Format("Items <b>1</b>-<b>{0}</b> out of <b>{1}</b>", NumberOfItemsInComboBox, NumberOfItems)
Else
e.Message = "No matches"
End If
e.EndOfItems = (NumberOfItemsInComboBox >= NumberOfItems)
End Sub
Protected Sub rlv_ItemInserting(ByVal sender As Object, ByVal e As Telerik.Web.UI.RadListViewCommandEventArgs) Handles rlv.ItemInserting
Dim ComboBox As Telerik.Web.UI.RadComboBox = e.ListViewItem.FindControl("RadComboBox1")
If Not String.IsNullOrWhiteSpace(ComboBox.SelectedValue) Then
Dim UserID As Integer = ComboBox.SelectedValue
Dim UserName As String = ComboBox.Text
Me.Users.Add(New UserInfo(UserID, UserName))
Else
e.Canceled = True
End If
End Sub
<Serializable()>
Public Class UserInfo
Private _UserID As Integer
Private _UserName As String
Public ReadOnly Property UserID As Integer
Get
Return _UserID
End Get
End Property
Public ReadOnly Property UserName As String
Get
Return _UserName
End Get
End Property
Public Sub New(ByVal UserID As Integer, ByVal UserName As String)
_UserID = UserID
_UserName = UserName
End Sub
End Class
End Class
After you have inserted the new item, set the InsertItemPosition to None:
RadListView1.InsertItemPosition = RadListViewInsertItemPosition.None
radlistview1.IsItemInserted=false;
or set e.canceled=false after save click

DropDownList AutoPostback fires when Asynchronous Postback occurrs

Well I have a strange problem.
I have a page with 2 DropDownLists on it and a custom web-user-control. The custom web user control has an UpdatePanel within it, and an Ajax Timer control within the UpdatePanel to periodically update a listing of stuff.
When I "drop-down" one of the DropDownLists and hover over (not click on) an option while the Timer control within the UpdatePanel asynchronously posts back to the server, the DropDownList "autopostbacks" to the server!
I'm trying to figure out why an asynchronous postback would cause the DropDownList to act as if I selected/clicked on an option so that I can find a way around this issue.
Now it's really simple to reproduce this problem.
Create a Web User control called "TimerUpdatedListing"...this is the ASPX code markup for the web user control:
<%# Control Language="vb" AutoEventWireup="false" CodeBehind="TimerUpdatedListing.ascx.vb" Inherits="MyNamespace.TimerUpdatedListing" %>
<div style="width: 150px; height: 150px; overflow: auto; border: solid 1px navy;">
<asp:UpdatePanel ID="anUpdatePanel" runat="server">
<ContentTemplate>
<asp:Repeater ID="aRepeater" runat="server">
<ItemTemplate>
<div style="border-bottom: solid 1px #EEC900; margin: 3px; padding: 2px;">
Id:
<%#Eval("Id")%>
<br />
Time:
<%#Eval("Time")%>
</div>
</ItemTemplate>
</asp:Repeater>
<asp:Timer ID="aTimer" runat="server" Interval="2000">
</asp:Timer>
</ContentTemplate>
</asp:UpdatePanel>
</div>
This is the VB.NET server side code for the web user control:
Public Partial Class TimerUpdatedListing
Inherits System.Web.UI.UserControl
Private _aListOFThings As List(Of Things)
Private Sub aTimer_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles aTimer.Tick
If Session("_aListOfThings") Is Nothing Then
_aListOFThings = New List(Of Things)
Else
_aListOFThings = CType(Session("_aListOfThings"), List(Of Things))
End If
If _aListOFThings.Count > 9 Then
_aListOFThings = New List(Of Things)
End If
_aListOFThings.Add(New Things((_aListOFThings.Count + 1).ToString, Now.ToString("hh:mm:ss")))
Session("_aListOfThings") = _aListOFThings
aRepeater.DataSource = _aListOFThings
aRepeater.DataBind()
End Sub
Private Class Things
Private _time As String
Private _id As String
Public Property Time() As String
Get
Return _time
End Get
Set(ByVal value As String)
_time = value
End Set
End Property
Public Property ID() As String
Get
Return _id
End Get
Set(ByVal value As String)
_id = value
End Set
End Property
Public Sub New(ByVal id As String, ByVal time As String)
_id = id
_time = time
End Sub
End Class
End Class
Now, in an ASPX page called WebForm1.aspx, add 2 DropDownLists and the web user control:
<%# Page Language="vb" AutoEventWireup="false" CodeBehind="WebForm1.aspx.vb" Inherits="MyNamespace.WebForm1" %>
<%# Register Src="TimerUpdatedListing.ascx" TagName="TimerUpdatedListing" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true">
<asp:ListItem Text="1" Value="1" />
<asp:ListItem Text="2" Value="2" />
<asp:ListItem Text="3" Value="3" />
<asp:ListItem Text="4" Value="4" />
<asp:ListItem Text="5" Value="5" />
</asp:DropDownList>
<asp:Label ID="selectedValue1" runat="server"></asp:Label>
<br />
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="true">
<asp:ListItem Text="a" Value="a" />
<asp:ListItem Text="b" Value="b" />
<asp:ListItem Text="c" Value="c" />
<asp:ListItem Text="d" Value="d" />
<asp:ListItem Text="e" Value="e" />
</asp:DropDownList>
<asp:Label ID="selectedValue2" runat="server"></asp:Label>
<br />
<br />
<uc1:TimerUpdatedListing ID="TimerUpdatedListing1" runat="server" />
</div>
</form>
</body>
</html>
Here is the VB.NET server side code for the WebForm1.aspx page:
Public Partial Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If String.IsNullOrEmpty(Request.Params("ddl1")) = False Then
selectedValue1.Text = Request.Params("ddl1")
End If
If String.IsNullOrEmpty(Request.Params("ddl2")) = False Then
selectedValue2.Text = Request.Params("ddl2")
End If
End Sub
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Response.Redirect(Request.Url.LocalPath + "?ddl1=" + DropDownList1.SelectedValue.ToString, True)
End Sub
Private Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.SelectedIndexChanged
Response.Redirect(Request.Url.LocalPath + "?ddl2=" + DropDownList2.SelectedValue.ToString, True)
End Sub
End Class
Thanks,
-Frinny
Here is an example of using triggers to trigger your update panel. Put the timer.tick event as a trigger and see what happens
http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-updatepanel-triggers
PS: I don't think the timer has to be included within the update panel. I actually build my timers in the codebehind and keep them out of the markup all together.
I attempted two different solutions to this problem.
The first thing I did was to check the Request.Params("__EVENTTARGET") to see if it matched the DropDownList. If it matched then I would call the Response.Redirect() method.
For example:
Public Partial Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If String.IsNullOrEmpty(Request.Params("ddl1")) = False Then
selectedValue1.Text = Request.Params("ddl1")
End If
If String.IsNullOrEmpty(Request.Params("ddl2")) = False Then
selectedValue2.Text = Request.Params("ddl2")
End If
End Sub
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
Dim ctrlNameThatCausedPostback As String = Request.Params("__EVENTTARGET")
If String.IsNullOrEmpty(ctrlNameThatCausedPostback) = False AndAlso Page.FindControl(ctrlNameThatCausedPostback) Is DropDownList1 Then
Response.Redirect(Request.Url.LocalPath + "?ddl1=" + DropDownList1.SelectedValue.ToString, True)
End If
End Sub
Private Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.SelectedIndexChanged
Dim ctrlNameThatCausedPostback As String = Request.Params("__EVENTTARGET")
If String.IsNullOrEmpty(ctrlNameThatCausedPostback) = False AndAlso Page.FindControl(ctrlNameThatCausedPostback) Is DropDownList2 Then
Response.Redirect(Request.Url.LocalPath + "?ddl2=" + DropDownList2.SelectedValue.ToString, True)
End If
End Sub
End Class
I noticed that this didn't always work. There were times when I selected an option in the DropDownList and the Redirect wouldn't take place because the timer tick and the selected index changed event happened at the same time.
So the second approach I took was to check to see if the page is in an asynchronous postback to the server. If it was, then I knew that it was the timer tick event taking place and that the Redirect shouldn't occur.
For example:
Public Partial Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If String.IsNullOrEmpty(Request.Params("ddl1")) = False Then
selectedValue1.Text = Request.Params("ddl1")
End If
If String.IsNullOrEmpty(Request.Params("ddl2")) = False Then
selectedValue2.Text = Request.Params("ddl2")
End If
End Sub
Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
If ScriptManager.GetCurrent(Me.Page).IsInAsyncPostBack = False Then
Response.Redirect(Request.Url.LocalPath + "?ddl1=" + DropDownList1.SelectedValue.ToString, True)
End If
End Sub
Private Sub DropDownList2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList2.SelectedIndexChanged
If ScriptManager.GetCurrent(Me.Page).IsInAsyncPostBack = False Then
Response.Redirect(Request.Url.LocalPath + "?ddl2=" + DropDownList2.SelectedValue.ToString, True)
End If
End Sub
End Class
This helped, and the likelihood that the Redirect would occur properly was better than the previous approach; however, it still isn't 100%.
-Frinny

Resources