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
Related
I am creating a query for a SqlDataSource in ASP.NET from code behind.
My code is as following:
Dim SqlDataSource1 As New SqlDataSource()
Dim SQL As String
' If Not IsPostBack Then
SqlDataSource1.ID = "sqlexpsearch"
Me.Page.Controls.Add(SqlDataSource1)
Dim connectionString As String
Dim connection As SqlConnection
connectionString = ConfigurationManager.ConnectionStrings("exam2ndconnection").ToString
connection = New SqlConnection(connectionString)
SqlDataSource1.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("exam2ndconnection").ConnectionString
If opname.Checked = True Then
SQL = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where name = '%'+ #srname +'%' OR ADDRESS ='%'+ #srname +'%' order by TR_DAte DESC,NAME "
SqlDataSource1.SelectParameters.Add("#srname", UCase(txtitem.Text))
SqlDataSource1.SelectCommand = SQL
End If
If opchno.Checked Then
SqlDataSource1.SelectCommand = "select SRNO,tr_date as Date ,MailMethod,SpeedId,Content,ExYear,Exroll as No,NAME,Address from dispatch where rtrim(exroll) ='" & txtitem.Text & "' order by tr_Date,exroll desc"
End If
GridView1.DataSource = SqlDataSource1
GridView1.DataBind()
I get this error:
Must declare the scalar variable "#srname".
on the line of code:
Gridview1.DataBind()
Please help to resolve this problem.
I would avoid trying to inject (add) a sql datasource into a page. (they don't persist anyway - you would have to re-inject each time).
However, DO keep in mind that any data aware control ALWAYS will automatic persist for you anyway.
The above information is thus great, since then you don't even have to bother with the sql data source. This is especially so in your example - you want to fill out a dropdown list, a grid view - whatever. In those cases? Just shove into that control a datatable - and your off to the races.
As noted, a lot of us use + prefer using code in place of a data source on the page - I find them rather messy and a pain to work with anyway.
In fact, what I will often do is say drop in a listbox, or even a grid view. I then use the wizard to create new data source - lay out the grid real nice and fast. I then go into the markup, remove the data source conrol that appears in the page.
Also, don't forget to remove the DataSourceID = from the Gridview markup (or whatever control you using).
This lets me still use the wizards to create the gridview, listview etc. but then I delete that extra junk, and wind up with a nice clean page without all that extra stuff in the page - (which is a pain to control from code anyway).
So, say for your example?
Try coding it this way:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
LoadGrid()
End If
End Sub
Sub LoadGrid()
Using conn As New SqlConnection(ConnectionStrings("exam2ndconnection").ConnectionString)
Dim strSQL As String = ""
strSQL = "SELECT SRNO, tr_date as Date, MailMethod, SpeedId, Content, ExYear, Exroll as No, " &
"[Name], Address FROM dispatch "
Dim strWhere As String = ""
Using cmdSQL As New SqlCommand(strSQL, conn)
If opName.Checked Then
strWhere = "([Name] Like '%'+ #srname +'%' OR ADDRESS = '%'+ #srname +'%') "
cmdSQL.Parameters.Add("#srname", SqlDbType.NVarChar).Value = txtitem.Text
End If
If opchno.Checked Then
If strWhere <> "" Then strWhere &= " AND "
strWhere &= "(Rtrim(exroll) = #exroll)"
cmdSQL.Parameters.Add("#exroll", SqlDbType.NVarChar).Value = txtitem.Text
End If
If strWhere <> "" Then
cmdSQL.CommandText &= " WHERE " & strWhere
End If
' add our sorting
cmdSQL.CommandText &= " ORDER BY tr_Date, exroll DESC"
conn.Open()
Dim rstData As New DataTable
rstData.Load(cmdSQL.ExecuteReader)
GridView1.DataSource = rstData
GridView1.DataBind()
End Using
End Using
End Sub
A few things:
YES DO NOT forget to put the load of such data inside of the PostBack = false.
Load the results into a datatable (there are several reasons for this, but one BIG reason is that the row data bound event will have full use of that data row - including the WHOLE data row - even columns that are NOT part of the gridview.
note careful in above.
If you don't check "opname", then the criteria is not added.
if you don't check "opchno", then the criteria is not added.
if you check either one - the criteria for that option is added
so, if you check none, no criteria
if you check both, then you get both filters. So this allows you add even more options, and they are ALL optional - and we "clumative" can build up selection criteria this way.
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
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.
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.
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