Addhandler for dynamically created controls - asp.net

I've written a piece of code that retrieves the number of photo albums a person has and then dynamically creates the same amount of ImageButtons within the 'AlbumsPanel' panel.
I have given Each ImageButton a unique Id (Grabs AlbumId from Albums table within sql server) and would like to be able to identify which ImageButton the user clicks (Store the myAlbum.ID in a variable some how so it can be used in a later stored procedure to retrieve pictures that belongs to that album).
spRetrieveAlbums example code:
SELECT AlbumId FROM dbo.Albums WHERE Id = #CurrentUserId;
SET #AlbumCount = ##ROWCOUNT;
Main.aspx.vb code:
Connection.Open()
sqlReader = spRetrieveAlbums.ExecuteReader()
If sqlReader.HasRows() Then
Do While sqlReader.Read()
Dim myAlbum = New ImageButton
myAlbum.ID = sqlReader.GetInt32(0)
myAlbum.Visible = True
myAlbum.Width = 160
myAlbum.Height = 160
myAlbum.BorderStyle = BorderStyle.Solid
myAlbum.BorderColor = Drawing.Color.WhiteSmoke
myAlbum.BorderWidth = 1
AlbumsPanel.Controls.Add(myAlbum)
Loop
End If
sqlReader.Close()
AlbumCount = spRetrieveAlbums.Parameters("#AlbumCount").Value
Connection.Close()
AlbumCountSpan.InnerHtml = "Albums: " & AlbumCount
Someone mentioned using an addhandler to the code but I'm not 100% sure how they work! Can someone point me in the right direction and give an example?

Add in loop block:
AddHandler myAlbum.Click, AddressOf NameOfMethode
or separate metode each iteration, using lambda:
AddHandler myAlbum.Click, Sub() someAction
In the first way you should identify the sender. like:
Sub NameOfMethode(sender As Object, e As ImageClickEventArgs)
Label1.Text = Ctype(sender, ImageButton).ID
End Sub
but in the second way you can write Appropriate function for each iteration. like:
AddHandler myAlbum.Click, Sub() Label1.Text = sqlReader(0)

Related

ASP repeater sorting ItemDataBound

I'm having a bit of trouble with ASP Repeaters and trying to sort the data.
So on Page_Load I obtain the datasource as below...
Protected Overloads Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not (Page.IsPostBack) Then
'No need to re-load Occasion because it's done in the PreLoad event
Me.Header.Title = "OCP - " + Occasion.Checklist.name
pnlStatistics.Visible = Not (Occasion.isClosed)
pnlClose.Visible = SecurityHelper.HasRole(SecurityMatchOption.AtLeast, SecurityRole.Manager, _relevantTeam) And Not (Occasion.isClosed)
'initially assume checklist can be closed. any un-signed off task in the item_databound event will disable it.
btnClose.Enabled = True
'Fix Issue 63: rptTask.DataSource = _db.vw_tasklists.Where(Function(o) o.occasionId = Occasion.id).ToList()
rptTask.DataSource = _db.vw_tasklists.Where(Function(o) o.occasionId = Occasion.id).OrderBy(Function(t) t.taskDueDate).ThenBy(Function(t) t.taskDueTime)
However within ItemDataBound we recalculate the task duedate.
Private Sub rptTask_ItemDataBound(sender As Object, e As RepeaterItemEventArgs) Handles rptTask.ItemDataBound
' Get the data relating to this task 'row'
Dim t = CType(e.Item.DataItem, vw_tasklist)
If e.Item.ItemType = ListItemType.Header Then
Dim thDueDate = CType(e.Item.FindControl("thDueDate"), HtmlTableCell)
thDueDate.Visible = Not (Occasion.isClosed)
End If
'securable buttons
If e.Item.ItemType = ListItemType.Item Or e.Item.ItemType = ListItemType.AlternatingItem Then
' Dynamically create a span element named TASKnnnn, which will be referenced from
' 'child page' links back to this page in order to vertically reposition at the selected task
Dim span = New HtmlGenericControl("span")
span.ID = "TASK" & t.taskId
span.ClientIDMode = ClientIDMode.Static ' prevent ASP.NET element ID mangling
e.Item.FindControl("lblTaskName").Parent.Controls.AddAt(0, span) ' hook it into the repeater row
Dim btnSignoff = CType(e.Item.FindControl("btnSignOff"), Button)
Dim btnComment = CType(e.Item.FindControl("btnComment"), Button)
Dim btnAmend = CType(e.Item.FindControl("btnAmend"), Button)
Dim btnView = CType(e.Item.FindControl("btnView"), Button)
Dim lblSoTime = CType(e.Item.FindControl("lblSOTime"), Label)
Dim lblDueDate = CType(e.Item.FindControl("lblDueDate"), Label)
Dim lblTaskId = CType(e.Item.FindControl("lblTaskId"), Label)
Dim lblTaskName = CType(e.Item.FindControl("lblTaskName"), Label)
lblTaskId.Text = CType(t.taskId, String)
lblTaskName.Text = t.taskName
Dim time = (If(t.taskDueTime Is Nothing, New TimeSpan(0, 23, 59, 59), TimeSpan.Parse(t.taskDueTime)))
Dim dueDateTime As DateTime = (Occasion.started.Date + time)
'Setup up due DateTime for Daily Tasks
Select Case DirectCast(t.taskDayTypeId, helpers.Constants.enDayType)
Case helpers.Constants.enDayType.Daily
lblDueDate.Text = dueDateTime.ToString("dd/MM/yyyy HH:mm")
Exit Select
Case Else
'Calculate the actual due date for non-daily tasks
Dim calculator = New Calculator()
Dim calId = t.taskCalendarId
Dim taskMonthDay = "1"
If Not t.taskMonthDayId Is Nothing Then
taskMonthDay = CType(t.taskMonthDayId, String)
End If
Dim monthDay = _db.MonthDays.First(Function(m) m.id = CInt(taskMonthDay))
Dim calendar As Model.Calendar = Nothing
If Not calId is Nothing Then
calendar = _db.Calendars.First(Function(x) calId.Value = x.id)
End If
Dim potDate = calculator.GetActualDueDate(dueDateTime, monthDay.monthDay, t, calendar)
dueDateTime = (potDate.Date + time)
lblDueDate.Text = dueDateTime.ToString("dd/MM/yyyy HH:mm")
Exit Select
End Select
Therefore once the data is displayed in the repeater the sorting is wrong. I need to be able to sort the data after the due date re-calculation. How is this possible?
Thanks
You can to move the ItemDataBound logic up into the original query:
rptTask.DataSource = _db.vw_tasklists.
Where(Function(o) o.occasionId = Occasion.id).
Select(
Function(r)
'Fill in the logic here so the DueProperty has your real Due Date
New With {.Row = r, .DueDate = r.TaskDueDate + r.TaskDueTime}
End Function
OrderBy(Function(t) t.DueDate). ' Now we only need one OrderBy (the time is already included).
Select(Function(r) r.Row) 'But we do want to select back to the original record for the databinding
'And the ToList() was probably NEVER needed or helpful in this situation
Moreover, since this looks like linq-to-sql I might break that up a bit, so we cleanly separate what we expect to execute on the database from what we expect to execute on the web server:
'This runs on the databsae
Dim sqlData = _db.vw_tasklists.
Where(Function(o) o.occasionId = Occasion.id)
'This runs on the web server
rptTask.DataSource = sqlData.
Select(
Function(r)
'Fill in the logic here so the DueProperty has your real Due Date
New With {.Row = r, .DueDate = r.TaskDueDate + r.TaskDueTime}
End Function
OrderBy(Function(t) t.DueDate). ' Now we only need one OrderBy (the time is already included).
Select(Function(r) r.Row) 'But we do want to select back to the original record for the databinding
'And the ToList() was probably NEVER needed or helpful in this situation
Of course, you'll get the best results if you start putting information into the database such that you can effectively sort your data correctly there at the outset.

VB ASP.NET - Add code to a control that is created by code behind

I'm using VB ASP.NET and would like to know how to add code to a control that is created by code behind?
For example in my Main.aspx.vb file I have the following code:
Connection.Open()
spRetrieveAlbums.ExecuteNonQuery()
ReturnValue = spRetrieveAlbums.Parameters("#ReturnValue").Value
Connection.Close()
For I = 1 To ReturnValue
Dim myAlbum = New ImageButton
myAlbum.Visible = True
myAlbum.Width = 150
myAlbum.Height = 150
myAlbum.BorderStyle = BorderStyle.Solid
myAlbum.BorderColor = Drawing.Color.WhiteSmoke
myAlbum.BorderWidth = 1
AlbumsPanel.Controls.Add(myAlbum)
Next I
ReturnValue stores the number of albums a person has (Using SQL Server stored procedure ##ROWCOUNT) and displays the same amount of ImageButtons within the 'AlbumsPanel' Panel on the web page.
I would like to use response.redirect("Albums.aspx") on a click event on any of the ImageButtons but not sure how I can achieve this. Any suggestions?
you have created dynamically and you can use a delegate for min.VB10 and like that,
AddHandler myAlbum.Click, _
Sub(sender As Object, e As EventArgs)
//To Do for Response
End Sub

Checkbox list keep disabled

Trying to use checkbox lists in (calendar booking system). The checkbox should be disabled and red if there are any data in the database against the date and hour. This all work perfectly here is the code. Using vb.net
OK i found a way how to clear the checkboxes
Dim i As Integer
Dim chboxItem As ListItem
For Each chboxItem In CheckBoxListMon.Items
i += 1
If (i Mod 1 = 0) Then
chboxItem.Enabled = True
End If
Next
Protected Sub Page_LoadComplete(sender As Object, e As EventArgs) Handles Me.LoadComplete
Try
strQuery = "SELECT BookingDate, checkBoxItem, BookRegUserID,Booked FROM bookings INNER JOIN checkboxitems where checkBoxItem = BookingTime"
MySQLCmd = New MySqlCommand(strQuery, dbCon)
dbCon.Open()
DR = MySQLCmd.ExecuteReader
While DR.Read
bookDate = DR.Item("BookingDate")
bookTime = DR.Item("checkBoxItem")
bookRegID = DR.Item("BookRegUserID")
booked = DR.Item("Booked")
Dim test As String = bookTime.ToString()
Select Case True
Case bookDate = lblMonday.Text And CheckBoxListMon.Items.FindByValue(test) IsNot Nothing
CheckBoxListMon.Items.FindByValue(bookTime).Enabled = False
CheckBoxListMon.Items.FindByValue(bookTime).Attributes.Add("Style", "color: red;")
End Select
End While
DR.Close()
dbCon.Close()
Catch ex As Exception
End Try
End Sub
When the page load it would not change the ones from the database. But when i reload the page it will actually work perfect.
Where can i put the check just to be sure that they are already in the memory.
Any help will be much appreciated. Thanks all.
Petr
You need to refresh the data when another week is selected because you are using the same controls for each week. You should be able to do this in whatever control you are using to toggle through the weeks.
Page_LoadComplete can only be expedted to fire each time a page has completed loading, that is why your controls work when going to another page and back.

Changing DropDown Selected Item Based on Selected Value (ASP.NET)

I have a dropdown list on my page (ddlProgram) which is populated via a database query like so:
Using dbContext as IRFEntities = New IRFEntities
Dim getPrograms = (From p in dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddl.Program.DataBind()
End Using
So, for example, one might have a DataTextField of "Education" and an ID of "221".
Now, I prepopulate the form with information about the individual visiting the site (if available) - including the dropdown list like so:
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
ddlProgram.SelectedValue = getProspect.Program
End If
End If
The Program property contains a number that matches the ID of a Program. So, for example, this individual might have a Program of "221" which would match the "221" of Education mentioned above.
Currently the application successfully sets the SelectedValue to "221" for the DropDownList (ddlProgram), but the SelectedItem of the DDL remains the same (e.g., if it is initially "History" with an ID of "1" after the prepopulation it is "History" with an ID of "221").
What I'm trying to make happen is that the SelectedItem is updated to item which corresponds with the SelectedValue. So, in the end, if the individual has "221" for "Education" selected when the form is prepopulated they would see Education as the selected item and the selected value would be set correctly, whereas right now the form is showing the wrong SelectedItem but has the right SelectedValue behind the scenes.
Here is a more complete idea of the code flow from the Page_Load event:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Page.IsPostBack = False Then
' If prospect is coming from unique url
Dim prospect_url As String = Page.RouteData.Values("value")
' Save prospect_url into session variable
Session("prospect_url") = prospect_url
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the programs dropdown.
Dim getPrograms = (From p In dbContext.IRF_Program _
Order By p.name _
Select p)
ddlProgram.DataSource = getPrograms
ddlProgram.DataTextField = "name"
ddlProgram.DataValueField = "id"
ddlProgram.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Prepopulate the states dropdown.
Dim getStates = (From p In dbContext.IRF_States _
Order By p.name _
Select p)
ddlState.DataSource = getStates
ddlState.DataTextField = "name"
ddlState.DataValueField = "id"
ddlState.DataBind()
End Using
Using dbContext As IRFEntities = New IRFEntities
' Grab info. about prospect based on unique url.
Dim getProspect = (From p In dbContext.IRF_Prospects _
Where p.url = prospect_url _
Select p).FirstOrDefault
' If they have a record...
If getProspect IsNot Nothing Then
If getProspect.user_id Is Nothing Then
' Prepopulate the form with their information.
' These must have a value, so we need to make sure that no column is null in the database.
ddlProgram.SelectedValue = getProspect.program
txtFirst.Text = getProspect.first_name
txtLast.Text = getProspect.last_name
txtAddress.Text = getProspect.address
txtCity.Text = getProspect.city
ddlState.SelectedValue = getProspect.state
txtZip.Text = getProspect.zip
txtPhone.Text = getProspect.phone
txtEmail.Text = getProspect.email_address
txtYearEnrolling.Text = getProspect.enrolling_in
Else
' Redirect them to login.
Response.Redirect("login.aspx")
End If
End If
End Using
End If
End Sub
What you're doing looks like it should work. If you put a breakpoint after the setting of the value and check the SelectedItem text and value, do they appear as expected or mismatched?
Use the Immediate Window to check:
ddlProgram.SelectedItem.Text
ddlProgram.SelectedItem.Value
If they appear the same then I would presume the binding code is being refired and the list is being regenerated with the first item being selected.
To check this put a break point on the binding code and see if it is fired more than once and correct the order of the methods appropriately.
ADDED:
If it works on your local environment it should work when published, if the code is the same? Looking at your code, I'd start by seperating out some of the databinding code into seperate methods rather than have everything in Page_Load, one becuase it's good practice and two because it will make debugging easier. Further than that I'm not sure what else to suggest.

ASP CascadingDropDown Control Causes IE Script timeout

Before a page is loaded, I use a subroutine to link DropDownList controls together:
Private Sub CreateCascadingDropDown(ByVal category As String, ByRef parentDDL As DropDownList, ByRef targetDDL As DropDownList)
Dim CDDL As New CascadingDropDown
With CDDL
.Category = category
If Not parentDDL Is Nothing Then
parentDDL.Items.Clear()
.ParentControlID = parentDDL.ID
End If
targetDDL.Items.Clear()
.TargetControlID = targetDDL.ID
.PromptText = SharedWeb.GC_SELECTONE
.PromptValue = "-1"
.LoadingText = "Please wait..."
.ServicePath = "/ajax/InvestmentProcess.asmx"
.ServiceMethod = "GetTaxo"
End With
'Page.ClientScript.RegisterForEventValidation(CDDL.UniqueID)
targetDDL.Parent.Controls.Add(CDDL)
End Sub
When the web service method is called, it executes the following code. Based on the category, it gets the appropriate data from the adapter.
<WebMethod()> _
Public Function GetTaxo(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
log.Debug("GetSegmentTaxonomy(" + category + ") -> {" + knownCategoryValues + "}")
Dim kv As StringDictionary = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues)
Dim adapter As New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter
Dim rows As DataRowCollection
Select Case category
Case InvestmentEdit.ST_SEG_ARCH
rows = New SegmentTaxonomyTableAdapters.SEGMENT_ARCHITECTURE_TableAdapter().GetData().Rows
Case InvestmentEdit.ST_LOB
If kv.ContainsKey(InvestmentEdit.ST_SEG_ARCH) Then
log.Debug("found seg architecture - > " + kv(InvestmentEdit.ST_SEG_ARCH))
rows = New SegmentTaxonomyTableAdapters.LINE_OF_BUSINESSTableAdapter().GetData(kv(InvestmentEdit.ST_SEG_ARCH)).Rows
End If
End Select
If Not rows Is Nothing Then
Dim results As New List(Of CascadingDropDownNameValue)
For Each row As DataRow In rows
log.Debug("ROW >>>> " + row("lov_label").ToString() + " : " + row("lov_cd").ToString())
results.Add(New CascadingDropDownNameValue(row("lov_label"), row("lov_cd")))
Next
Return results.ToArray
End If
Return Nothing
End Function
There are about 5 drop downs I need to link together. The top-level drop down control (myDDL) loads fine if it is the only one linked like so:
CreateCascadingDropDown("MyCat",Nothing,myDDL)
But when I link a second drop down control, Internet Explorer gives a script timeout. If I keep allowing the script to run, it just keeps giving me the prompt. If elect to discontinue running the script, I get a Method Error 12031 or Error 500 (and yes, I have the ScriptService() declaration in my web service file). Any ideas on what's causing this?
It turns out I just needed to add the following control from the Ajax Control Toolkit:
<ajax:ToolkitScriptManager ID="tsm" runat="server" />
Instead of .TargetControlID = targetDDL.ID I needed to use:
.TargetControlID = targetDDL.UniqueId

Resources