Handling events of dynamically created controls in asp.net - asp.net

I have a button which is not created dynamically. When I click on that button the number of lines in a textbox are counted. I store that in the variable called count. Depending on value of count I create buttons in panel.
Up to now it is working properly.
Now the click event of those buttons is not firing.
I have tried to google my question. But everywhere I got the same answer. Create the controls in Page_Init event. But how is it possible? I am getting the value of count from a textfile's lines, and that value of count decides how many button will be created in the panel.
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
btnAllowList.Add(btnAllow)
tdAllow.Controls.Add(btnAllow)
The code for btnAllow_Click
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
For x As Integer = 0 To btnAllowList.Count - 1
If sender.ID.SubString(3) = btnAllowList(x).ID.Substring(3) Then
Dim lineCount = IO.File.ReadAllLines(PendingRequestsPath).Length
Dim reader As New System.IO.StreamReader(DocumentViewersPath)
Dim allLines As New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Dim DocumentViewerAlreadyExists As Boolean = False
For i As Integer = 0 To lineCount - 1
If ReadLine(i, allLines) = lblRequestorsList(x).Text Then
DocumentViewerAlreadyExists = True
Exit For
End If
Next
If DocumentViewerAlreadyExists = False Then
Dim Writer As System.IO.StreamWriter = IO.File.AppendText(DocumentViewersPath)
Writer.WriteLine(lblRequestorsList(x).Text)
End If
Dim line As String = ""
Dim r As IO.StreamReader = IO.File.OpenText(PendingRequestsPath)
Dim strFile As New ArrayList
While r.Peek <> -1 ' Loop through the file
line = r.ReadLine 'Read the next available line
' Check to see if the line contains what you're looking for.
' If not, add it to an ArrayList
If Not line.Contains(lblRequestorsList(x).Text) Then
strFile.Add(line)
End If
r.Close()
' Because we want to replace the content of the file, we first
' need to delete it.
If IO.File.Exists(PendingRequestsPath) Then
IO.File.Delete(PendingRequestsPath)
End If
' Create a StreamWriter object with the same filename
Dim objWriter As New IO.StreamWriter(PendingRequestsPath, True)
' Iterate through the ArrayList
For Each item As ArrayList In strFile
objWriter.WriteLine(item) ' Write the current item in the ArrayList to the file.
Next
objWriter.Flush()
objWriter.Close()
End While
End If
Next
End Sub

This worked for me:
Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
Dim NumberOfControls As Integer = 10
Session("CreateControls") = NumberOfControls
End Sub
Protected Sub btnAllow_Click(ByVal sender As Object, ByVal e As System.EventArgs)
'This will be executed when clicking on the newly created buttons.
End Sub
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If Session("CreateControls") IsNot Nothing Then
For x As Integer = 0 To Convert.ToInt32(Session("CreateControls"))
Dim btnAllow As New Button
btnAllow.Text = "Allow"
btnAllow.ID = "btA" & x
AddHandler btnAllow.Click, AddressOf btnAllow_Click
Panel1.Controls.Add(btnAllow)
Next
End If
End Sub

Related

Dynamically Added Event Handler Not Firing in VB.NET

For some reason when I click the "Remove" button nothing happens. I'm assuming that this has something to do with view state and losing the handlers on page load, though I still can't make sense of it. I'm recreating the handler every time the page loads, why isn't this working?
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then
If Not IsNothing(fileUpload.PostedFile) AndAlso fileUpload.PostedFile.ContentLength > 0 Then
_files = TryCast(Session("FilesToSend"), List(Of document))
_files.Add(New Document(fileUpload.FileName, fileUpload.FileBytes, fileUpload.FileBytes.Length))
loadTable()
End If
Else
Session("FilesToSend") = New List(Of document)
End If
End Sub
Private Sub loadTable()
Dim count As Integer = 0
For Each doc In _files
Dim r As New TableRow()
'Add Filename Cell
Dim filenameCell As New TableCell()
filenameCell.Text = doc.filename
r.Cells.Add(filenameCell)
'Add Size Cell
Dim sizeCell As New TableCell()
sizeCell.Text = doc.fileSize
r.Cells.Add(filenameCell)
'Add Remove Button Cell
Dim deleteButton As New Button
Dim deleteCell As New TableCell()
With deleteButton
.Text = "Remove"
'.ID = "deleteButton" + count.ToString()
deleteCell.Controls.Add(deleteButton)
AddHandler deleteButton.Click, AddressOf deleteRow_Click
End With
r.Cells.Add(deleteCell)
'AddHandler deleteButton.Click, New EventHandler(AddressOf deleteRow_Click)
'Add Row to Table
uploadedDocumentsTable.Rows.Add(r)
count += 1
Next
End Sub
Protected Sub deleteRow_Click(sender As Object, e As System.EventArgs)
_files = TryCast(Session("FilesToSend"), List(Of Document))
Dim deleteButton = TryCast(sender, Button)
_files.RemoveAt(sender.ID)
loadTable()
End Sub
Well after some more trial and error I finally figured it out. So the first issue was that I needed to add ".CausesValidation = False". This triggered the Postback, but then I needed to do some rearranging to make sure the controls were still getting loaded. Here's what worked:
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
If IsPostBack Then
_files = TryCast(Session("FilesToSend"), List(Of Document))
If Not IsNothing(fileUpload.PostedFile) AndAlso fileUpload.PostedFile.ContentLength > 0 Then
_files.Add(New Document(fileUpload.FileName, fileUpload.FileBytes, fileUpload.FileBytes.Length))
End If
Else
Session("FilesToSend") = New List(Of document)
End If
loadTable()
End Sub
Private Sub loadTable()
uploadedDocumentsTable.Rows.Clear()
Dim count As Integer = 0
For Each doc In _files
Dim r As New TableRow()
'Add Filename Cell
Dim filenameCell As New TableCell()
filenameCell.Text = doc.filename
r.Cells.Add(filenameCell)
'Add Size Cell
Dim sizeCell As New TableCell()
sizeCell.Text = doc.fileSize
r.Cells.Add(filenameCell)
'Add Remove Button Cell
Dim deleteButton As New Button
Dim deleteCell As New TableCell()
With deleteButton
.Text = "Remove"
.CausesValidation = False
.ID = count.ToString()
deleteCell.Controls.Add(deleteButton)
AddHandler deleteButton.Click, AddressOf deleteRow_Click
End With
r.Cells.Add(deleteCell)
'Add Row to Table
uploadedDocumentsTable.Rows.Add(r)
count += 1
Next
End Sub
Protected Sub deleteRow_Click(sender As Object, e As System.EventArgs)
_files.RemoveAt(sender.ID)
loadTable()
End Sub
You forgot to add the button to the Form. Modify it this way:
'Add Remove Button Cell
Dim deleteButton As New Button
Dim deleteCell As New TableCell()
With deleteButton
.Text = "Remove"
'.ID = "deleteButton" + count.ToString()
deleteCell.Controls.Add(deleteButton)
AddHandler deleteButton.Click, AddressOf deleteRow_Click
End With
Me.Controls.Add(deleteButton)
Surprise, you button is now located at position (0, 0), and the event is now listened to. You may want to modify it's position too, I guess.
Have fun!

ASP VB Stuck on Dynamic Controls, Viewstate, and Postback. Could really use some help to get back on track

I've been reading posts and articles and just getting a little confused and consequently burning through time I don't have at the moment
Can someone look at my code and tell me where I've gone wrong?
Partial Class PayerContacts
Inherits System.Web.UI.Page
Dim connStrDRContacts As String = ConfigurationManager.ConnectionStrings("DRContacts_SQL").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
navBuild()
End Sub
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
If IsPostBack Then
LoadContacts(ViewState("objSender"))
End If
End Sub
Private Function navBuild() As Integer
Dim SQLstrDRs As String = "SELECT * FROM DRList"
Dim DbConnDRs As SqlConnection = New SqlConnection(connStrDRContacts)
DbConnDRs.Open()
Dim dtDRsTemp As New DataTable
Dim SQLAdapterDRs As New SqlDataAdapter(SQLstrDRs, DbConnDRs)
SQLAdapterDRs.Fill(dtDRsTemp)
'Loop through each row of the DataView to create HTML table data
Dim NewTableRow As New TableRow
For Each row As DataRow In dtDRsTemp.Rows
'CREATE table with button to display contacts related to client (one to many)
Dim NewTableButton As LinkButton = New LinkButton
NewTableButton.ID = "btnDRName" & NewTableText
NewTableButton.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler NewTableButton.Click, AddressOf LoadContacts
Next
Return 0
End Function
Protected Sub LoadContacts(sender As Object, e As EventArgs)
Dim LoopCount As Integer = 0
Dim SQLstrLoadTable As String = "SELECT * FROM ContactList WHERE DRVendor = '" & sender.Text.ToString & "'"
and so on....
SQLAdapterLoadTable.Fill(dtLoadTableTemp)
Dim NewTableRow As New TableRow
For Each row As DataRow In dtLoadTableTemp.Rows
'CREATE Accordion to display data
NewAccordion.ID = "ContactAccordion" & LoopCount
NewAccordion.Visible = True
blah, blah...
'SET Pane
NewAccordionPane.HeaderContainer.ID = "PaneHeader" & LoopCount
NewAccordionPane.ContentContainer.ID = "PaneContent" & LoopCount
'CREATE button to open ModalPopup to EDIT each record
Dim imgGear As New ImageButton
imgGear.ID = "btnGear" & row!ID.ToString
imgGear.ViewStateMode = UI.ViewStateMode.Enabled
AddHandler imgGear.Click, AddressOf EditRecord
'LOAD Pane
NewAccordionPane.HeaderContainer.Controls.Add(NewHeaderTable)
NewAccordionPane.ContentContainer.Controls.Add(New LiteralControl(NewTableText))
ViewState("objSender") = sender
End Sub
Protected Sub EditRecord(ByVal sender As Object, ByVal e As EventArgs)
'Open ModalPopup to edit record
popup.Show()
pnlAddEdit.Visible = True
End Sub
End Class
The Infinities Loop articles on ViewState and Dynamic Controls should really be read by every Webforms developer: -
http://mocha.mojoskins.com/SharedFiles/Download.aspx?pageid=566&mid=786&fileid=38
http://weblogs.asp.net/infinitiesloop/TRULY-Understanding-Dynamic-Controls-_2800_Part-1_2900_
The examples are in C# but you should be able to figure out what's going on, it's the same base class library after all.

asp.net gridview without database

Hi guys I have a question. Is there some way to populate a gridview in asp.net without using a database? I'm using a gridview to show information but I've seen that everytime I try to insert more rows to the grid the last row is changed with a new one and overwrites the data
I'm using the following code:
Dim dtsetinform As New DataSet
Dim datatableinfo As New DataTable("fill")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
dtsetinform.Tables.Add(datatableinfo )
gridfactura.DataSource = datatableinfo
datatableinfo.Columns.Add("Name") '
datatableinfo.Columns.Add("Quantity")
datatableinfo.Columns.Add("Price")
Session("fill") = datatableinfo
End Sub
Public Sub agregarfilas(ByVal total As Integer)
datatableinfo = Session("fill")
Dim row As DataRow = datatableinfo .NewRow
row("Name") = ddserviciotxt.Text
row("Quantity") = cantidadtxt.Text
row("Price") = total
datatableinfo .Rows.Add(row)
ViewState("tablainViewState") = datatableinfo
datatableinfo .AcceptChanges()
gridfactura.DataSource = datatableinfo
gridfactura.DataBind()
End Sub
Protected Sub btnagregar_Click(sender As Object, e As EventArgs) Handles btnagregar.Click
Dim result As Integer
Dim price As Integer = preciotxt.Text
Dim quantity As Integer = cantidadtxt.Text
result = price * quantity
agregarfilas(result)
End Sub
you need to put the code in the page load in
if not Page.IsPostBack then
your code
end if

ASP.net Vb.Net Label.Text not updating

In my VB.net ASP application, i have some ASPTREEVIEW where, on page load there is a Label, to which i set some value. After clicking on any row, i catch that value & assign it to the label.
But suddenly that label value is not updating by the chosen value. As if i check it via debugging the value, the value changes, but when i use Lable.text = chosen_value... It sets the value, but it is not actually changing on the html page. HTML shows the old value.
What will be the problem, i am not getting it.
Imports DevExpress
Imports DevExpress.Xpo
Imports DevExpress.Data
Imports DevExpress.Data.Filtering
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Public testvar As Integer = 35
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim xpcol As New XPCollection(Of WCSOEE.WcsGCObject)
Dim GCObj1 As WCSOEE.WcsGCObject
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
Dim SelectedGCObject As WCSOEE.WcsGCObject
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Label2.Text
If Label2.Text = "" Then
Label2.Text = 10
End If
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
' WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = CInt(Label2.Text)
Next
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
If masterKeyvalue IsNot Nothing Then
SelectedGCObject = masterKeyvalue.DataItem
Else
SelectedGCObject = xpcol.Object(31)
End If
' MsgBox(SelectedGCObject.GCName)
MsgBox(Label2.Text)
If IsPostBack = False Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
End Sub
Protected Function calculatehours(Oid As Integer)
xpocolLogAvailability.Session = DevExpress.Xpo.XpoDefault.Session
Dim logavail As New XPCollection(Of WCSOEE.LogAvailability)
Dim gcobjlist As New XPCollection(Of WCSOEE.WcsGCObject)
gcobjlist.Filter = CriteriaOperator.Parse("[Oid]=?", Oid)
Dim filter As CriteriaOperator
Dim ds As New DataTable
Dim Series As New DevExpress.XtraCharts.Series
Dim Filter1 As New DevExpress.XtraCharts.DataFilter
' Label2.Text = Oid
logavail.Filter = CriteriaOperator.Parse("GCObject.Oid=?", Oid)
Filter1.ColumnName = "Oid"
Filter1.Condition = XtraCharts.DataFilterCondition.Equal
Filter1.Value = Oid
Dim arr1(32) As Long
'For i As Int16 = 1 To 32
' arr1(i) = 0
'Next
'For Each gcobj As WCSOEE.LogAvailability In logavail
' arr1(gcobj.Status) = arr1(gcobj.Status) + gcobj.Duration
'Next= ""
'ds.Columns.Add(New DataColumn("Name", System.Type.GetType("System.Int32")))
For Each Siris As DevExpress.XtraCharts.Series In WebChartControl1.Series
WebChartControl1.Series(Siris.Name).DataFilters.Item(0).Value = Oid
Next
WebChartControl1.RefreshData()
'For i As Int16 = 1 To 32
' ds.Rows.Add(i, arr1(i))
'Next
'ASPxListBox1.DataSource = ds
'ASPxListBox1.DataBind()
Return Oid
End Function
Protected Sub ASPxTreeList1_CustomCallback(sender As Object, e As DevExpress.Web.ASPxTreeList.TreeListCustomCallbackEventArgs) Handles ASPxTreeList1.CustomCallback
End Sub
Protected Sub ASPxTreeList1_FocusedNodeChanged(sender As Object, e As System.EventArgs) Handles ASPxTreeList1.FocusedNodeChanged
Dim masterKeyvalue As DevExpress.Web.ASPxTreeList.TreeListNode = ASPxTreeList1.FocusedNode
Dim SelectedGCObject As WCSOEE.WcsGCObject = masterKeyvalue.DataItem
' MsgBox(SelectedGCObject.GCName)
If IsPostBack Then
Label2.Text = calculatehours(SelectedGCObject.Oid)
End If
MsgBox(IsPostBack)
MsgBox(Label2.Text)
End Sub
End Class
Post some code so we can see exactly what your doing, without seeing anything so far ensure you have an If statement in your page load to only apply the label text if the current request is not a postback other wise the the label will be set to this on every request.
If Not IsPostBack() Then
lblSomeLabel.Text = "Page load text"
End If

Maintaining Checkbox State in a Listview Control Pagination ASP.NET

I Have a web form in a asp.net web form 3.5. The listview has a checkbox on the item template, I am trying to retain the state of the checkboxes through pagination . Once I can page through records and preserver this state I need to send this to a print page which takes those ids...I have this working, but it will print only the records on each pagination. Please see live website:
http://rgvpreferred.com/ProviderSearch.aspx
Can you please check my code and suggest how can this be done, the code below is not working.
Protected Sub ListView1_ItemCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewCommandEventArgs) Handles ListView1.ItemCommand
Dim myButtonPrint1 As Button = CType(ListView1.FindControl("printButton1"), Button)
If e.CommandSource Is myButtonPrint1 Then
Dim recordsId As New List(Of String)
For Each lvi1 As ListViewItem In ListView1.Items
Dim chb1 As CheckBox = IIf(lvi1.FindControl("CheckBoxPrintProvider1") Is Nothing, IIf(lvi1.FindControl("CheckBoxPrintProvider3") Is Nothing, lvi1.FindControl("CheckBoxPrintProvider4"), lvi1.FindControl("CheckBoxPrintProvider3")), lvi1.FindControl("CheckBoxPrintProvider1"))
If chb1.Checked = True Then
Dim param1 As String
param1 = DirectCast(lvi1.FindControl("lblId1"), Label).Text
recordsId.Add(param1)
End If
Next
' Store in session to be pulled out in the Printable Page
Session("Records") = recordsId
Response.Redirect("PrintableProviderList.aspx")
End If
End Sub
'Trying to Preserve states
Private ReadOnly Property IDs() As List(Of Integer)
' Create a list of ID's that are selected. ID's is the primary
' Key for this table
Get
If Me.ViewState("IDs") Is Nothing Then
Me.ViewState("IDs") = New List(Of Integer)()
End If
Return CType(Me.ViewState("IDs"), List(Of Integer))
End Get
End Property
Protected Sub AddRowstoIDList()
' Loop through all the current items in the Listview
For Each lvi As ListViewDataItem In ListView1.Items
' Find the checkbox in each row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' If the checkbox is ticked then add the corresponding ID to our private
' list
If (Not (chkSelect) Is Nothing) Then
' Get the ID from the datakeynames property
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
If (chkSelect.Checked AndAlso Not Me.IDs.Contains(ID)) Then
' Add the ID to our list
Me.IDs.Add(ID)
ElseIf (Not chkSelect.Checked AndAlso Me.IDs.Contains(ID)) Then
' Not checked - remove the ID from our list
Me.IDs.Remove(ID)
End If
End If
Next
End Sub
Protected Sub ListView1_PagePropertiesChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles ListView1.PagePropertiesChanging
AddRowstoIDList()
End Sub
Protected Sub ListView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewSortEventArgs) Handles ListView1.Sorting
AddRowstoIDList()
End Sub
Protected Sub ListView1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ListView1.ItemDataBound
' Get each Listview Item on DataBound
Dim lvi As ListViewDataItem = e.Item
If (lvi.ItemType = ListViewItemType.DataItem) Then
' Find the checkbox in the current row
Dim chkSelect As CheckBox = CType(lvi.FindControl("CheckBoxPrintProvider1"), CheckBox)
' Make sure we're referencing the correct control
If (Not (chkSelect) Is Nothing) Then
' If the ID exists in our list then check the checkbox
Dim ID As Integer = Convert.ToInt32(ListView1.DataKeys(lvi.DisplayIndex).Value)
chkSelect.Checked = Me.IDs.Contains(ID)
End If
End If
End Sub
you have to save the selected checkboxes before pagination .
see this link. it should help you:
http://evonet.com.au/maintaining-checkbox-state-in-a-listview/

Resources