Visual basic Webform ASP.net - asp.net

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.

Related

How can I create a self-incrementing column for a DataGridView?

I need to add a self-incrementing column to a DataGridView. Every time a row is added to the grid I want to increment the No column.
My Form_Load code:
Private Sub SAP_OrdenVenta_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
DataGridView1.ColumnCount = 6
DataGridView1.Columns(0).Name = ("No")
DataGridView1.Columns(1).Name = ("NoArticulo")
DataGridView1.Columns(2).Name = ("Descripcion")
DataGridView1.Columns(3).Name = ("Cantidad")
DataGridView1.Columns(4).Name = ("Precio")
DataGridView1.Columns(5).Name = ("Total")
End Sub
The DataGridView Button Click event for the add button:
Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
Dim articulo, cantidad As Integer
Dim precio, total1 As Double
Dim i As Integer = 0
articulo = txtArticulo.Text.Trim()
cantidad = txtCantidad.Text.Trim()
precio = txtPrecio.Text.Trim()
total1 = txtPrecio.Text.Trim()
'Agrego Linea a DataGridView
Dim row As String() = New String() {1, articulo, "No disponible", cantidad, precio, total1}
DataGridView1.Rows.Add(row)
End Sub
How can I make this work?
Private Sub btnAgregar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAgregar.Click
Dim LastIndex As Integer = DataGridView1.Rows.Count - 1
Dim LastNo As Integer = Integer.Parse(DataGridView1.Rows(LastIndex).Cells(0).Value)
Dim NewNo As String = (LastNo + 1).ToString()
Dim row As String() = New String() {NewNo, txtArticulo.Text, "No disponible", txtCantidad.Text, txtPrecio.Text, txtPrecio.Text}
DataGridView1.Rows.Add(row)
End Sub
Take note, however: if this view is loaded from a real database table, you almost always want to rely on your database's ability to generate ID values. Otherwise, this is a huge race condition waiting to blow up.

how to get array element as output in vb asp.net2010

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

how to decode an ASCII code back to string in ASP.Net

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

Repeater forgetting how many items to display when next button is clicked

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

Access Multiple Dynamic Dropdownlists selected Value - ASP.Net

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

Resources