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.
Related
I'm dynamically adding htmlvideo controls to my web form based on the number of videos present on the server folder. This part works fine. All the videos show up and can be played. I add the 'onended' event as an attribute and the function in my code behind, but this event won't fire. I'm aware that since these controls are added after the fact I have to add a listener, but just don't know how.
This is the code that adds the controls
Dim SavePath As String = "e:\ftproot\images\TechNet\"
Dim Directory As New DirectoryInfo(SavePath)
Dim allFiles As IO.FileInfo() = Directory.GetFiles("*.mov")
Dim VidCtr As Integer = 1
For Each singlefile In allFiles
Dim myVid As New HtmlVideo
myVid.Src = "https://www.rawauto.com/images/TechNet/" & singlefile.Name
myVid.Attributes.Add("height", 140)
myVid.Attributes.Add("runat", "server")
myVid.Attributes.Add("type", "video/mp4")
myVid.Attributes.Add("controls", "controls")
myVid.Attributes.Add("onended", "VidPlayed")
myVid.Attributes.Add("id", "Vid" & VidCtr)
Panel1.Controls.Add(myVid)
Dim myLbl As New Label
myLbl.Text = Replace(UCase(singlefile.Name), ".MOV", "")
myLbl.Width = 250
myLbl.CssClass = "VidStyle"
myLbl.Font.Name = "calabri"
myLbl.Font.Bold = True
LPanel.Controls.Add(myLbl)
Next
This is the function I'm trying to fire once the user has finished watching the video:
Protected Sub VidPlayed(sender As Object, e As EventArgs)
Dim Tech As New SqlConnection("server=RAW-OTT; Initial Catalog=TechNet; Integrated Security=True;")
Dim vid As HtmlVideo = sender
Dim vidurl As String = vid.Src
VidName = Replace(vidurl, "https://www.rawauto.com/images/TechNet/", "")
If Len(VidName) > 50 Then
VidName = Mid(VidName, 1, 50)
End If
Dim SqlStr As String = "Select * From TechTube Where Video = '" & VidName & "'"
Dim ttA As New SqlDataAdapter(SqlStr, Tech)
Dim ttT As New DataTable
ttA.Fill(ttT)
If ttT.Rows.Count = 0 Then
SqlStr = "Insert Into TechTube Values ('" & VidName & "', 1, 0)"
Dim tCmd As New SqlCommand(SqlStr, Tech)
Tech.Open()
tCmd.ExecuteNonQuery()
Tech.Close()
Else
SqlStr = "Update TechTube Set Hits = Hits + 1 Where Video = '" & VidName & "'"
Dim tCmd As New SqlCommand(SqlStr, Tech)
Tech.Open()
tCmd.ExecuteNonQuery()
Tech.Close()
End If
RateLabel.Visible = True
RatingBox.Visible = True
End Sub
This is an old ViewState problem for any dynamic control, and has nothing specific to do with video.
Remember, every PostBack rebuilds the entire page from scratch, including your dynamic controls. If you still want to see these controls after a postback (which includes all server events), you must re-add them to the page. Additionally, you need a control's ViewState restored if you want an event fired for the control during this PostBack, and for the ViewState to restore the control must be added back to the reconstructed page before the Page_Load event runs. Page_Init or Page_PreInit can work well for this.
Finally, consider the performance implications here. Do you really want to rebuild the entire page on every user interaction, or is it perhaps time to learn to use javascript to process these things, with maybe a web api that only has to receive a javascript request without causing an entire page cycle both on your server and in the user's browser?
Just a few of the many other times this has been asked and answered:
Dynamic Event Handler not Firing
dynamically added buttons not firing click event c#
dynamically created button click event not firing
Dynamically Added DropDownlists Are Not Firing SelectedIndexChanged Event
ASP.NET: Viewstate and programmatically adding user controls
Click events on Array of buttons
VB ASP dynamic button click event not hitting handler event
I have some inconsistent behaviour with a drop down list.
When it postback and the selected index is 1, it goes through and works as it should, gets the data, builds the UI, and writes everything to the screen.
if the selected index is 2 then it goes through the BuildUI() method, and then goes through the loop again thinking that the selected index is 0 and then doesn't build the UI.
this is the code
Protected Sub Page_Complete() Handles Me.LoadComplete
If _IsAuth = True Then
'if user is authorised to use the application, and the drop down menu has UK or GE
'selected then the the UI will be build for the user.
If Page.IsPostBack And ddlCharterVersion.SelectedIndex > 0 Then
BuildUI()
'once the UI has been built the dropdown list is to be hidden
ScriptManager.RegisterStartupScript(Me, GetType(Page), "ddlCharterVersion", "$('#paymentType').hide();", True)
Else
'if the user is not authorised they are passed a message showing that they are not authorised from the master
'page and the panel holding the divs and information will be hidden
ScriptManager.RegisterStartupScript(Me, GetType(Page), "hidePayments", "$('#panelHead').hide();", True)
End If
End If
End Sub
Protected Sub ddlCharterVersion_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ddlCharterVersion.SelectedIndexChanged
ddlCharterVersion.Enabled = False
End Sub
And this is the dropdown on the page.
<div class="col-md-10 pull-left "><asp:dropdownlist runat="server" width="200px" id="ddlCharterVersion" AutoPostBack="True">
<asp:ListItem Value="-- Select Charter Version -- ">-- Select Charter Version -- </asp:ListItem>
<asp:ListItem Value="UK">UK</asp:ListItem>
<asp:ListItem Value="GE">GE</asp:ListItem>
</asp:dropdownlist></div>
When debugging the application I don't hit any errors that should cause the page to postback.
what puzzles me the most is that selected index position 1 works fine, position 2 does not.
If anyone can see directly what the issue is I would be very grateful for your assistance.
--update--
-- update 2 --
when debugging this, I never hit any of the exceptions, and have a breakpoint on each of them and none of them are ever hit.
Protected Sub BuildUI()
'gets the next record for payment
GetNextRecordForPayment()
If noRecords = False Then
'if there are records, concatenate the list of payments into one row in a list
ConcatenateListOfPayments()
''write the records to the UI
writeRecordsToUI()
End If
End Sub
Protected Sub GetNextRecordForPayment()
Try
''if a user already has a record locked and has refreshed the page for any reason
''get this record back until they pass it to the excptions queue or validate for payment
'UserHasRecordLocked is returned as an object. Either as the contactId of the locked record or False
Dim UserHasRecordLocked = CheckForLockedRecord()
Dim lockedRecord As Long
Dim contactIdParam As New SqlParameter("#LockedRecord", SqlDbType.BigInt)
Dim charterVersionParam As New SqlParameter("#CharterVersion", SqlDbType.VarChar)
charterVersionParam.Value = ddlCharterVersion.SelectedValue
'check the type of object of UserHasRecordLocked
If UserHasRecordLocked.GetType = GetType(Long) Then
'if it has a record then assign the value of UserHasRecordLocked
'to the sqll parameter.
contactIdParam.Value = UserHasRecordLocked
Else
'else give it a default value
contactIdParam.Value = 99999
End If
'place all parameters into a list object of sql parameter
'this has been done this way so that you dont have to be
'precious or careful of where you place your parametss
Dim listOfParam As New List(Of SqlParameter)
listOfParam.Add(contactIdParam)
listOfParam.Add(charterVersionParam)
''gets all records due to be paid
Dim dt As DataTable
'get the first payment \ contact back in a datatable.
'brings back all the parts of the payment, ie redress, d&i, hmrc deductions
'and later concatenates them into one line
dt = DataAccessLayer.FindRecords(listOfParam, _charterPayments, "dbo.usp_getFirstRecordForPayment")
If dt.Rows.Count = 0 Then
noRecords = True
'if there are no records inform the user that there are no payments to be made this day.
ScriptManager.RegisterStartupScript(Me, GetType(Page), "noPayments", "$('#noPayments').modal();", True)
Exit Sub
End If
'build a list of payments using a payee class
BuildListOfPayments(dt)
'using MoreLINQ to get the First or Default record to get the most basic of information out.
Dim paymentInfo = listOfPayments.FirstOrDefault()
''if payment is an IVA, C&R or Deceased Case this will be thrown to the exceptions for manual handling.
If paymentInfo.isException = True Then
'record the exceptions
Dim recorded = RecordNewException(paymentInfo.ContactId, paymentInfo.ContactPartId, paymentInfo.ExceptionReason, True)
If recorded = True Then
'post the page back to get the next record and start the loop again
Response.Redirect(Request.RawUrl, False)
Context.ApplicationInstance.CompleteRequest()
End If
End If
Try
'set the class level variable
_PaymentCategory = paymentInfo.Category
Catch ex As Exception
Dim recorded = RecordNewException(paymentInfo.ContactId, paymentInfo.ContactPartId, "Cannot match complaint against a category type", True)
If recorded = False Then
Response.Redirect(Request.RawUrl, False)
Context.ApplicationInstance.CompleteRequest()
End If
End Try
'lock the record so that no other user can be working on this at the same time
LockRecord(dt)
If paymentInfo.charterVersion = "GE" Then
'if the payment is coming from GE Charter then complete various checks
checkGeCharterPayments(paymentInfo)
ElseIf paymentInfo.charterVersion = "SANUK" Then
'if the payment is coming from GE Charter then complete various checks
checkSanCharterPayments(paymentInfo)
Else
Exit Sub
End If
Catch sqlEx As SqlException
PassToErrorHandler(sqlEx, System.Reflection.MethodInfo.GetCurrentMethod().ToString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name)
Catch ex As Exception
PassToErrorHandler(ex, System.Reflection.MethodInfo.GetCurrentMethod().ToString(), System.Reflection.Assembly.GetExecutingAssembly().GetName().Name)
End Try
End Sub
i am having this problem if i set debug=false in web.config file.
i had a treeview where all the nodes are loaded dynamically from code pagehide during Page_Load event
if i set debug="true" this works fine if i add another node form a button and so on.
But if i set it to false. nodes are loaded correctly during If Not IsPostBack Then if i add a new node, it will show correctly but if there is another postback,the newly added button will be disappeared and data are loaded from the first postback and i have to close the web and reopen again to load the new nodes to load.
the data will always remains at the first postback if i set debug to false.
anyone know why i am not getting new data from subsequent postback instead of first postback if i set debug to false?
please take note that i only having this issue on internet explorer 11. chrome and firefox i does not have this issue .
below is my code
If Not IsPostBack Then
Try
masternode = New TreeNod
masternode.Text = "Scale Management"
masternode.Value = "-4"
sendscalenodes.Nodes.Add(masternode)
loadNodes()'load all nodes on pageload
Catch ex As Exception
End Try
End If
End Sub
Protected Sub btndepadd_Click(sender As Object, e As EventArgs) Handles btndepadd.Click
'add nodes code here
loadNodes()'reload all nodes to refresh the tree view
End Sub
Sub loadNodes()
DepGr1.Nodes.Clear()
dbconnection.connect()
masternode = New TreeNod
masternode.Text = "Data Management"
masternode.Value = "Data Management"
masternode.SelectAction = TreeNodeSelectAction.None
DepGr1.Nodes.Add(masternode)
Dim dr As SqlClient.SqlDataReader
Dim dr2 As SqlClient.SqlDataReader
Dim sql2 As String = Nothing
sql = "select * from [data group] where DG_parent=-3"
dr = dbconnection.dr(sql)
Do While dr.Read
parentnod = New EleapTreeNod
parentnod.Text = dr.Item(4)
parentnod.Value = dr("DG_ID")
DepGr1.Nodes.Add(parentnod)
sql2 = " select * from [data group] where DG_parent=" & dr.Item(0) & ""
dr2 = dbconnection.dr(sql2)
Do While dr2.Read
childnod = New EleapTreeNod
childnod.Text = dr2.Item(4)
childnod.Value = dr2("DG_ID")
parentnod.ChildNodes.Add(childnod)
Loop
dr2.Close()
Loop
dr.Close()
dbconnection.ConClose()
DepGr1.ExpandAll()
End Sub
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)
I have created an VB.NET page to record views for ads and will call page from img src.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim insert_number As Integer = 0
Dim ad_id As Integer = 0
If Request.QueryString("adid") Is Nothing Then
ad_id = 0
Else
If Not Integer.TryParse(Request.QueryString("adid"), ad_id) Then
ad_id = 0
End If
End If
Dim connectStr As String = System.Configuration.ConfigurationManager.AppSettings("connectStr").ToString()
Dim myconnection As SqlConnection = New SqlConnection(connectStr)
Dim mySqlCommand As SqlCommand
myconnection.Open()
Try
mySqlCommand = New SqlCommand("sp_record", myconnection)
mySqlCommand.CommandType = CommandType.StoredProcedure
mySqlCommand.Parameters.AddWithValue("#record_id", ad_id)
insert_number = mySqlCommand.ExecuteNonQuery()
Catch ex As Exception
End Try
myconnection.Close()
Dim oBitmap As Bitmap = New Bitmap(1, 1)
Dim oGraphic As Graphics = Graphics.FromImage(oBitmap)
oGraphic.DrawLine(New Pen(Color.Red), 0, 0, 1, 1)
'Response.Clear()
Response.ContentType = "image/gif"
oBitmap.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Gif)
'oBitmap.Dispose()
'oGraphic.Dispose()
End Sub
Unless I comment oBitmap.Save line, the code runs twice and it makes two inserts (store prcoedure runs twice) to Database.
I have tried AutoEventWireup = "true" and "false" at #PAGE. "true" runs code twice, "false" did not do anything (no error) and did not give any output as well.
I have also tried following version of creating 1pixel image output but it did run twice as well (it requires aspcompat=true in #PAGE part):
'Response.ContentType = "image/gif"
'Dim objStream As Object
'objStream = Server.CreateObject("ADODB.Stream")
'objStream.open()
'objStream.type = 1
'objStream.loadfromfile("c:\1pixel.gif")
'Response.BinaryWrite(objStream.read)
Any ideas are welcome.
You may want to do an onload function for the image to see why it's being called a second time. I'm guessing that it's getting loaded somewhere in the preload and then being called (.Save) during the page load as well and that's why you're seeing the double entry.
If you are trying to get unique page loads, you may want to try putting the oBitmap.Save line within a check for postback like this within the page load:
If Page.IsPostback = False Then
'Bitmap Code Here
End If
And see if that fixes it for you.
If you're loading data from a database, you'll want to make sure that it also is within that PostBack check (because a. you're loading the data twice and b. it can cause these double postbacks in some circumstances).
Edit: Wanted to edit code section to include all bitmap code, not just the save.
Not sure about the specifics, but that is a lot of code within in Page_Load function.
Generally, the way I would solve this type of problem is to have some sort of page arguments that you can check for in order to do the correct things. Either add some get/post parameters to the call that you can check for or check things like the Page.IsPostBack.
I realize this is an old post but I had an similar issue where the page was firing twice on the postback. I found several posts sugesting what is being dicusses here. However, what corrected my issue was setting the page directive property AutoEventWireup=false at the page level.
Here is a good article How to use the AutoEventWireup attribute in an ASP.NET Web Form by using Visual C# .NET that helped me solve this.
Hope this helps!
Risho