In this program I created one array, while clicking on the get Button it does not show any output because the str variable is empty. How should I get proper output...
Partial Class dynamic_array
Inherits System.Web.UI.Page
Dim s(2) As String
Dim str As String
Protected Sub btn_save_Click(sender As Object, e As System.EventArgs) Handles btn_save.Click
Dim i As Integer = 0
For i = 0 To s.Length - 1
s(i) = InputBox("enter name " + (i + 1).ToString)
Next
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
Dim i As Integer = 0
str = ""
For i = 0 To s.Length - 1
str &= s(i) + vbCrLf
Next
MsgBox(str)
End Sub
End Class
You can use Session or ViewState to store the Array values..
try like this
Partial Class dynamic_array
Inherits System.Web.UI.Page
Dim s(2) As String
Dim str As String
Protected Sub btn_save_Click(sender As Object, e As System.EventArgs) Handles btn_save.Click
Dim i As Integer = 0
For i = 0 To s.Length - 1
s(i) = InputBox("enter name " + (i + 1).ToString)
Next
ViewState("Array")=s
End Sub
Protected Sub btn_get_Click(sender As Object, e As System.EventArgs) Handles btn_get.Click
Dim i As Integer = 0
str = ""
s= ViewState("Array")
For i = 0 To s.Length - 1
str &= s(i) + vbCrLf
Next
MsgBox(str)
End Sub
End Class
Hope this will help, Mark useful if it's helps.
In Asp.Net all variables set on the page level are reset on every postback. Thats why s-variable is always empty on get-button click.
You could save this information for example in the viewstate
Viewstate("MyData") = "Something"
I encourage you to familiarize your self with Asp.Net web forms basic state management: http://msdn.microsoft.com/en-us/library/50x35554(v=vs.80).aspx
Related
I'm trying to learn ASP.NET with VB.
I've created a customized Panel control with below code.
Public Class RowPanel
Inherits Panel
Private WithEvents pnlMain As New Panel
Private btnRack() As Button
Public Sub New(Optional ByRef NoOfRacks As Integer = 8)
createPanel(NoOfRacks)
End Sub
Public Sub createPanel(ByVal NoOfRacks As Integer)
With pnlMain
.Height = 600
.Width = 200
.BackColor = Drawing.Color.BurlyWood
.BorderStyle = WebControls.BorderStyle.Dashed
End With
ReDim btnRack(NoOfRacks - 1)
For i = 1 To NoOfRacks
btnRack(i - 1) = New Button
With btnRack(i - 1)
.Width = pnlMain.Width.Value - 20
.ID = "Rack" & Guid.NewGuid().ToString("N")
.Text = "Rack" & i
'AddHandler .Click, AddressOf rackbutton_Click
End With
Next
Dim bt As Button
For Each bt In btnRack
AddHandler bt.Click, AddressOf rackbutton_Click
Next
For b As Integer = 0 To btnRack.GetUpperBound(0)
Dim brk As New LiteralControl("</br>")
pnlMain.Controls.Add(btnRack(b))
pnlMain.HorizontalAlign = WebControls.HorizontalAlign.Center
pnlMain.Controls.Add(brk)
Next
Me.Controls.Add(pnlMain)
End Sub
Protected Sub rackbutton_Click(sender As Object, e As EventArgs)
Dim clickedbtn As Button
clickedbtn = CType(sender, Button)
MsgBox(clickedbtn.ID.ToString)
End Sub
End Class
My problem is the rackbutton_Click event is not firing when I clicked a button in the panel.
Main webform code:
Public Class WebForm1
Inherits System.Web.UI.Page
Private dynamicPnlIDs As New List(Of String)
Const _MaxRacks As Integer = 10
Dim rck As Integer = 1
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Session("dynamicBtnIDs") IsNot Nothing Then
dynamicPnlIDs = DirectCast(Session("dynamicBtnIDs"), List(Of String))
For Each pnlID As String In dynamicPnlIDs
Dim rk As Integer
rk = Right(pnlID, pnlID.Length - (1 + pnlID.IndexOf(":"c)))
Dim pnl As New RowPanel(rk)
Dim tblCell As New TableCell
pnl.ID = Right(pnlID, pnlID.IndexOf(":"c) - 1).ToString()
tblCell.Controls.Add(pnl)
Table1.Rows(0).Controls.Add(tblCell)
Next
Else
dynamicPnlIDs = New List(Of String)()
End If
End Sub
Protected Sub Page_PreRender(sender As Object, e As EventArgs) Handles Me.PreRender
Session("dynamicBtnIDs") = dynamicPnlIDs
End Sub
Protected Sub addRow_Click(sender As Object, e As EventArgs) Handles addRow.Click
rck = TextBox1.Text
If Not (rck > 0 And rck <= _MaxRacks) Then
MsgBox("Invalid Entry!" & vbCrLf & "Please enter a value between 1 &" & _MaxRacks & ".", vbOKOnly, "Error")
TextBox1.BackColor = Drawing.Color.PaleVioletRed
Exit Sub
Else
TextBox1.BackColor = System.Drawing.ColorTranslator.FromHtml("#CDCDCD")
End If
Dim pnl As New RowPanel(rck)
Dim tblCell As New TableCell
pnl.ID = "pnl" & Guid.NewGuid().ToString("N")
tblCell.Controls.Add(pnl)
Table1.Rows(0).Controls.Add(tblCell)
dynamicPnlIDs.Add(pnl.ID & ":" & rck.ToString())
End Sub
End Class
Please help me.
(This is my first post, any advise is welcome)
Remove or comment out the following line and it should start working.
'.ID = "Rack" & Guid.NewGuid().ToString("N")
You can replace it with something meaningful, if you want to.
e.g.
.ID = pnlMain.UniqueID & "_Rack" & i.ToString
Not sure why the labels are not continuously switching.
I break-pointed it and it shows the counter resets everytime and so it should just be
continuously swapping through the numbers but it doesn't seem to be working
Thanks!
Public Class WebForm2 Inherits System.Web.UI.Page
Dim d As Integer() = {0, 1, 2, 3, 4}
Dim counter As Integer
Public Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Label1.Text = d(0)
Label2.Text = d(1)
Label3.Text = d(2)
Label4.Text = d(3)
Label5.Text = d(4)
End If
End Sub
Public Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim hold As Integer
counter = 0
hold = d(0)
Do While counter < 4
d(counter) = d(counter + 1)
counter += 1
Loop
Label1.Text = d(0)
Label2.Text = d(1)
Label3.Text = d(2)
Label4.Text = d(3)
Label5.Text = hold
End Sub
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
Dim hold As Integer
counter = 0
hold = d(0)
Do While counter < 4
d(counter) = d(counter + 1)
counter += 1
Loop
Label1.Text = d(0)
Label2.Text = d(1)
Label3.Text = d(2)
Label4.Text = d(3)
Label5.Text = hold
End Sub
End Class
I am not familiar with vb.net but I've created asp.net pages before so I am taking an educated guess here^^
When clicking the button a postback happens and the whole page gets reloaded and the array d is declared again.
The values you store in your array are lost after the Post-Back. For keeping data you could use Session or ViewState variables:
Session
ViewState
As I said this is for asp.net but it might help anyways.
Edit: I still think the data is somewhere lost in this d-array... What if you just leave out the array and have your button_Click event like this:
String temp = Label1.Text;
Label1.Text = Label2.Text;
Label2.Text = Label3.Text;
Label3.Text = Label4.Text;
Label4.Text = Label5.Text;
Label5.Text = temp;
Your array named d (is there a better name for this?) is being re-declared on every page-load (as it seems like it should be).
The problem is that you're not persisting the adjusted array values each page load. Instead, you're starting from scratch each time as others have suggested.
See the following URL for a lot of useful information about persisting state information in a web-forms application.
http://msdn.microsoft.com/en-us/library/vstudio/z1hkazw7(v=vs.100).aspx
As far as your code, you can try something along these lines to persist the values from the current array while setting it up for the next load.
Public Class WebForm2 Inherits System.Web.UI.Page
Private _dValues As Integer(19)
Private _currentValues As Integer(19)
Private _newValues As Integer(19)
Private _startIndex As Integer
Public Sub New()
_dValues = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}
_startIndex = 0
End Sub
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
If Page.IsPostBack Then 'Load values from form
For i As Integer = 0 To _currentValues.Length - 1 Step 1
_currentValues(i) = Request.Form(String.Concat("Hidden", i))
Next
_startIndex = Request.Form("StartIndex")
Else
_currentValues = _dValues 'First time around
End If
Dim position As Integer = _startIndex
For i As Integer = 0 To _currentvalues.Length - 1 Step 1
If position >= _newValues.Length Then
position = 0
End If
'Assign the current position in the new array equal to the current sequential value in the previous array
_newValues(position) = _currentValues(i)
position += 1
Next
End Sub
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Increment the counter every post back
If Page.IsPostBack Then
_startIndex += 1
End If
'Don't allow the counter to go outside the bounds of the array
If _startIndex >= _currentValues.Length Then
_startIndex = 0
End If
Me.StartIndex.Text = _startIndex 'Assign the value of the hidden field
End Sub
Public Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'Dynamically set label / hidden data
For i As Integer = 0 To _newValues.Length - 1 Step 1
CType(Page.FindControl(String.Concat("Label", i), Label).Text = _currentValues(i)
CType(Page.FindControl(String.Concat("Hidden", i), Hidden).Text = _newValues(i)
Next
End Sub
Protected Sub Timer1_Tick(ByVal sender As Object, ByVal e As EventArgs) Handles Timer1.Tick
'Dynamically set label / hidden data
For i As Integer = 0 To _newValues.Length - 1 Step 1
CType(Page.FindControl(String.Concat("Label", i), Label).Text = _currentValues(i)
CType(Page.FindControl(String.Concat("Hidden", i), Hidden).Text = _newValues(i)
Next
End Sub
End Class
Then in your form:
<asp:Hidden ID="StartIndex" runat="server" Value="" />
<asp:Label ID="Label1" runat="server" Value="" />
<asp:Hidden ID="Hidden1" runat="server" Value="" />
<asp:Label ID="Label2" runat="server" Value="" />
<asp:Hidden ID="Hidden2" runat="server" Value="" />
etc...
This code (or at least a version of it) will build a number of label and hidden input fields that will be used to display data and persist data. Each time the page is posted, the start index will be incremented, which will change the start position of the new values. While the current values will be based on what is posted back from the hidden inputs.
I Have a problem with decoding ASCII code back to string.
First I take a text input from user and convert it to ASCII code which is consecutively assigned to a label. Than I want to convert it from that label back to the normal string. But in stead of the string I receive a random symbols.
I believe it's because the function can't distinguish when a code for a certain letter starts and when it's finishes. Any Idea how can i set a delimiter or something like that? if ever it's going to solve the problem of course
this is the code i used:
Protected Sub Button4_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button4.Click
Label3.Text = ""
For x As Integer = 1 To TextBox3.Text.Length
Label3.Text &= CStr(Asc(Mid$(TextBox3.Text, x, 1)))
Next
End Sub
Protected Sub Button5_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button5.Click
Label4.Text = ""
For x As Integer = 1 To Label3.Text.Length
Label4.Text &= Chr(Mid$(Label3.Text, x, 1))
Next
End Sub
Try this out.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Label3.Text = ""
For x As Integer = 1 To TextBox3.Text.Length
Label3.Text &= CStr(Asc(Mid$(TextBox3.Text, x, 1))) & "|"
Next
End Sub
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button2.Click
Label4.Text = ""
Dim value As Integer = 0
Dim buf As String = ""
For x As Integer = 1 To Label3.Text.Length
If Mid$(Label3.Text, x, 1) <> "|" Then
buf &= Mid$(Label3.Text, x, 1)
Else
Label4.Text &= Chr(Val(buf))
buf = ""
End If
Next
End Sub
I have a repeater list that displays results in sets of 15. When you click the next button it shows the next 15 and so on.
I have added some buttons that will then filter the display to show the results in sets of 10, 25, 50.
When you click these it does work but when you click the next button it resets the display value to 15.
Below is the chunk of script:
Public Property CurrentPage() As Integer
Get
' look for current page in ViewState
Dim o As Object = Me.ViewState("_CurrentPage")
If o Is Nothing Then
Return 0
Else
' default to showing the first page
Return CInt(o)
End If
End Get
Set
Me.ViewState("_CurrentPage") = value
End Set
End Property
Protected Sub ItemsGet()
Dim pageSize As Integer = 15
ItemsGet(pageSize)
End Sub
Private Sub ItemsGet(ByVal pageSize As Integer)
' Read sample item info from XML document into a DataSet
' Populate the repeater control with the Items DataSet
Dim objPds As New PagedDataSource()
Dim selectedCategory As String = ddlCategory.SelectedValue.ToString()
Dim selectedCategoryIndex As Integer = ddlCategory.SelectedIndex
Dim selectedCategoryMonth As String = ddlCategoryMonth.SelectedValue.ToString()
Dim selectedCategoryMonthIndex As Integer = ddlCategoryMonth.SelectedIndex
Dim query = GetXmlDataSet()
If (Not String.IsNullOrEmpty(selectedCategory) And selectedCategoryIndex > 0) Then
query = query.Where(Function(x) x("SCategoryName") = selectedCategory)
End If
If (Not String.IsNullOrEmpty(selectedCategoryMonth) And selectedCategoryMonthIndex > 0) Then
query = query.Where(Function(x) x("SCategoryMonth") = selectedCategoryMonth)
End If
If (query.Count() > 0) Then
objPds.DataSource = query.CopyToDataTable().Rows
objPds.AllowPaging = True
objPds.PageSize = pageSize
objPds.CurrentPageIndex = CurrentPage
lblCurrentPage.Text = "Page: " + (CurrentPage + 1).ToString() + " of " + objPds.PageCount.ToString()
' Disable Prev or Next buttons if necessary
cmdPrev.Enabled = Not objPds.IsFirstPage
cmdNext.Enabled = Not objPds.IsLastPage
Display10.Enabled = True
Display25.Enabled = True
Display50.Enabled = True
categories.DataSource = objPds
categories.DataBind()
Else
CurrentPage = 0
categories.Controls.Clear()
cmdPrev.Enabled = False
cmdNext.Enabled = False
Display10.Enabled = False
Display25.Enabled = False
Display50.Enabled = False
lblCurrentPage.Text = "Page: 0 of 0 "
End If
End Sub
Private Sub Display10_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 10
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display25_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 25
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub Display50_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim pageSize As Integer = 50
CurrentPage = 0
ItemsGet(pageSize)
End Sub
Private Sub cmdPrev_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the previous page
CurrentPage -= 1
' Reload control
ItemsGet()
End Sub
Private Sub cmdNext_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Set viewstate variable to the next page
CurrentPage += 1
' Reload control
ItemsGet()
End Sub
Protected Sub ddlCategory_SelectedIndexChanged1(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
Protected Sub ddlCategoryMonth_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs)
CurrentPage = 0
ItemsGet()
End Sub
You need to 'persist' the number of items to get.
There are a few ways to do this....
Re-factor PageSize into a property with its backing kept in the viewstate, remember to initialise with appropriate default values.
Change the ItemsGet sub to use the property instead.
My vb is rusty!
Public Property PageSize() As Integer
Get
If Me.ViewState("PageSize") Is Nothing Then
Me.ViewState("PageSize") = 15
End If
Return CInt( Me.ViewState("PageSize") )
End Get
Set
Me.ViewState("PageSize") = value
End Set
End Property
I am adding multiple dynamic dropdownlists to my form.
I'm wanting to access the selected values of the dropdownlists on click of a button.
Private pnlDropDownList As Panel
Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As EventArgs) Handles Me.PreInit
'Create a Dynamic Panel
pnlDropDownList = New Panel()
pnlDropDownList.ID = "pnlDropDownList"
pnlDropDownList.BorderWidth = 1
pnlDropDownList.Width = 300
Me.form1.Controls.Add(pnlDropDownList)
'Create a LinkDynamic Button to Add TextBoxes
Dim btnAddDdl As New Button
btnAddDdl.ID = "btnAddDdl"
btnAddDdl.Text = "Add DropDownList"
AddHandler btnAddDdl.Click, AddressOf btnAdd_Click
Me.form1.Controls.Add(btnAddDdl)
'Recreate Controls
RecreateControls("ddlDynamic", "DropDownList")
End Sub
Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim cnt As Integer = FindOccurence("ddlDynamic")
CreateDropDownList("ddlDynamic-" & Convert.ToString(cnt + 1))
End Sub
Private Function FindOccurence(ByVal substr As String) As Integer
Dim reqstr As String = Request.Form.ToString()
Return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length)
End Function
Private Sub RecreateControls(ByVal ctrlPrefix As String, ByVal ctrlType As String)
Dim ctrls As String() = Request.Form.ToString().Split("&"c)
Dim cnt As Integer = FindOccurence(ctrlPrefix)
If cnt > 0 Then
For k As Integer = 1 To cnt
For i As Integer = 0 To ctrls.Length - 1
If ctrls(i).Contains((ctrlPrefix & "-") + k.ToString()) AndAlso Not ctrls(i).Contains("EVENTTARGET") Then
Dim ctrlID As String = ctrls(i).Split("="c)(0)
If ctrlType = "DropDownList" Then
CreateDropDownList(ctrlID)
End If
Exit For
End If
Next
Next
End If
End Sub
Private Sub CreateDropDownList(ByVal ID As String)
Dim ddl As New DropDownList()
ddl.ID = ID
ddl.DataSource = Me.odsNames
ddl.DataTextField = "Name"
ddl.DataValueField = "ID"
ddl.DataBind()
ddl.Items.Insert(0, New ListItem("All", -1))
ddl.SelectedIndex = 0
ddl.AutoPostBack = True
AddHandler ddl.SelectedIndexChanged, AddressOf OnSelectedIndexChanged
pnlDropDownList.Controls.Add(ddl)
Dim lt As New Literal()
lt.Text = "<br />"
pnlDropDownList.Controls.Add(lt)
End Sub
Protected Sub OnSelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
'Not used, want to get Values from button click
End Sub
Protected Sub cmdAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles cmdAdd.Click
Dim cnt As Integer = FindOccurence("ddlDynamic")
pnlDropDownList.Controls.Remove(pnlDropDownList.FindControl("ddlDynamic-" & Convert.ToString(cnt)))
End Sub
This is where I would like to check all dynamic dropdownlists and extract their selected values
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'' Check All dynamic Dropdownlists and retrieve selected values
End Sub
End Class
Any assistance would be much appreciated. thanks
You could use Linq to get the references of your dynamic DropDowns in the panel:
Dim allDdls = pnlDropDownList.Controls.OfType(Of DropDownList)()
For Each ddl In allDdls
Dim selectedValue = ddl.SelectedValue
Next