I am sure everyone who programmed with user controls for asp.net came across situations where you needed a certain way to check whether a user control has been loaded for the first time or it has been re-loaded. Has anyone come up with any other solutions other than setting hidden "currentOpenControl" flag(s). If you are wondering as to do I need to check whether control is open for first time or re-open again, then one of the big reasons is databinding. When the control is open for first time, that is when I want to databind, afterwards on re-open, if I databind again I will lose any changes user might have added.
So I am just wondering if anyone has a more elegant solution than setting flags whether control is open or not.
Thanks
The only way I've ever managed to do this is by using the ViewState...
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles MyBase.Load
If ViewState["postBack"] Is Nothing Then
' Do everything you'd normally do with Page.IsPostBack
ViewState["postBack"] = true
End
End Sub
Or for C#...
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["postBack"] == null)
{
// Do everything you'd normally do with Page.IsPostBack
ViewState["postBack"] = true;
}
}
You can get using this, its in VB.NET convert to c#
Private currentPage As Page = HttpContext.Current.Handler
If (Not currentPage.IsPostBack) Then
End if
Related
I have a Visual Basic Project where I have a page(Parent.aspx) with a user control inside(ChildForm.ascx), the user control have a checkboxlist where if the selection is changed I cause a postback and send an event
Protected Sub checkBoxList_checked(ByVal sender As Object, ByVal e As EventArgs) Handles checkBoxList.SelectedIndexChanged
RaiseEvent MyEvent(sender, e)
End Sub
to make a button invisible on the Parent view
Protected Sub ChildForm_MyEvent(ByVal sender As Object, ByVal e As EventArgs) Handles ChildForm.MyEvent
If condition Then
btnSave.Visible = False
Else
btnSave.Visible= True
End If
End Sub
When I debug I see the breakpoint hitting all the lines of code and the condition apply as intended, but the button is not hidden, I dont know why if is setting the correct value it never refreshes the Parent page to show the changes, even if it does cause a postback.
Please help
Check your page load events (load, prerender, prerenderComplete) to make sure you are not setting the visibility property in there. if you are, you may need to use
"If not IsPostBack"
I have very strange issues. I have used Update Panels before and never had issues but because I am grouping listviews I get the issues. I have about 4 Update Panels on a page which I call by using the panelname.update() in code behind, and used to all work.
Then because I had to group a bunch of listviews inside each other I had to use a PageLoad to DataBind rather than actually putting the data sources on the asp page. The data all works with Listview when page loads, but now the update panels don't work on async postback at all.
If I take out uppnlSOL.Update() in code behind all the rest start working again. The update panel that causes the issue is the same one that contains the listview with the DataBind.
ASP page has all panels have childrenastriggers="false" UpdateMode="Conditional" hence I call them all from code behind. I also tried removing the uppnlSOL.Update() from code behind and placing a trigger on the uppnlSOL on the asp page. As soon as it launches I get same result. I removed the trigger then the other 3 panels work again. I need all 4 working and
I am confused, its almost like its rendering while its trying to do the update panel or something. I even tried a pause for 3 seconds after DataBind then trying updatepanel.Update() and all 4 still didn't work.
I will try to put some code below of what is sort of going on.
Protected Sub Packing_Load(sender As Object, e As EventArgs) Handles Me.Load
If IsPostBack = False Then
lvSOLGrpDelAdd.DataSource = tblDespatchA.DespatchPackSOLGrpDelAdd_Get(IDSO:=hdnIDSO.Value)
lvSOLGrpDelAdd.DataBind()
End If
End Sub
Protected Sub lvSOLGrpDelAdd_RowDataBound(sender As Object, e As ListViewItemEventArgs) Handles lvSOLGrpDelAdd.ItemDataBound
Dim lvSOLGrpDelMeth As ListView = DirectCast(e.Item.FindControl("lvSOLGrpDelMeth"), ListView)
lvSOLGrpDelMeth.DataSource = tblDespatchA.DespatchPackSOLGrpDelMeth_Get(IDSO:=hdnIDSO.Value, IDGrpDelAdd:=DataBinder.Eval(e.Item.DataItem, "IDGrpDelAdd"))
lvSOLGrpDelMeth.DataBind()
End Sub
Protected Sub lvSOLGrpDelMeth_RowDataBound(sender As Object, e As ListViewItemEventArgs)
Dim lvSOL As ListView = DirectCast(e.Item.FindControl("lvSOL"), ListView)
lvSOL.DataSource = tblDespatchA.DespatchPackSOL_Get(IDSO:=hdnIDSO.Value, IDGrpDelAdd:=DataBinder.Eval(e.Item.DataItem, "IDGrpDelAdd").ToString, IDGrpDelMeth:=DataBinder.Eval(e.Item.DataItem, "IDGrpDelMeth").ToString)
lvSOL.DataBind()
End Sub
Protected Sub btnAllocateLine_Click(sender As Object, e As EventArgs)
Dim lvRow As Object = DirectCast(sender, Object).Parent
Dim hdnIDSOL As HiddenField = DirectCast(lvRow.FindControl("hdnIDSOL"), HiddenField)
Dim lstQtyAvail As DropDownList = DirectCast(lvRow.FindControl("lstQtyAvail"), DropDownList)
tblDespatchA.DespatchPackSOLAllocate_Save(IDSO:=hdnIDSO.Value, IDSOL:=hdnIDSOL.Value, AllocateQty:=lstQtyAvail.SelectedValue)
Bind()
End Sub
Protected Sub Bind()
uppnlDOL.DataBind()
uppnlDOL.Update()
uppnlDBox.DataBind()
uppnlDBox.Update()
uppnlFooter.DataBind()
uppnlFooter.Update()
'I HAVE TO REGET FROM DATABASE CHANGES THAT HAVE HAPPEN AND
'I KNOW THIS BIT WORKS BECAUSE I HAVE TESTED THE DATA.
lvSOLGrpDelAdd.DataSource = tblDespatchA.DespatchPackSOLGrpDelAdd_Get(IDSO:=hdnIDSO.Value)
lvSOLGrpDelAdd.DataBind()
uppnlSOL.Update() ' THIS BIT WHEN I PUT IN THIS MAKES ALL THE OTHER PANELS CRASH
End Sub
Here we go again I answer my own question because nobody would help, but I will help anyone else with similar situation because I'm nice.
The reason it crashed all the other panels is because on my ASP.net page had some generated code in there using <% Response.Write("stuff here") %> and because of using the Response.Write caused it crash.
The Update Panels are doing a async post back and me calling a Response.Write() at the same time as PanelName.Update() caused this issue. I am looking for another method to write to the screen without using response.write and that would solve my 2nd problem.
Any Ideas would be appreciated.
I'm having a problem with a Web Control that is dynamically created and inserted in my page. I create a couple of LinkButtons, depending on the data of the search that was made, and I'm trying to add an Event Handler to each of the Buttons, so it would filter the result.
The controls are initialized properly, but the event is never fired.
Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Init
Controls.Clear()
Dim btn As Controls.LocalizableLinkButton
For Each element As Generic.KeyValuePair(Of String, ResultFilterData) In m_list
btn = New LocalizableLinkButton
btn.ID = m_Name & "$lnk" & count
btn.Label = element.Value.Label.Append(" (" + CStr(element.Value.Count) + ")")
btn.CommandArgument = element.Value.Key
AddHandler btn.Click, AddressOf Me.btn_Click
Controls.Add(btn)
Next
End Sub
Since this code is in Page_Init all the controls should be recreated on a postback. (The LocalizableLinkButton is just an extension of a LinkButton to add multilingual features to the text).
The problem is that the method btn_Click is never called. The Link Buttons are properly initialized on the callback, with the same ID's as before. But the event doesn't fire.
I'm using ASP.Net 2.0
Any ideas?
I finally figured out the problem ASP.NET had with my Link Buttons.
The error was in using a '$' sign in my ID for each LinkButton. ASP.NET apparently uses the $ sign to build the control hierarchy when it creates the Postback Javascript. Therefore it thinks that the LinkButtons are nested within a control that does not exist. And so the events aren't fired of course.
Once I removed the $ signs it worked properly.
You probably want to put this piece of code in the Page_Load and see. It's generally advised not to access controls in this Page_Init as there is no guarantee of the controls been created at this stage.
I'm no VB guy but i put this into the codebehind of the default.aspx and it works fine.
protected void Page_Load(object sender, EventArgs e)
{
Button button = new Button();
button.Click += new EventHandler(button_Click);
button.Text = "test";
Form.Controls.Add(button);
}
void button_Click(object sender, EventArgs e)
{
throw new NotImplementedException();
}
I am new to asp.net. I am creating a ASP.net website using VB.net. So here's my problem
Dim myCounter as Integer = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click
myCounter = myCounter + 1
Label1.Text = myCounter.ToString()
end Sub
As expected I always get Label Text as 0 each time click the button. How to I create global variable and increment it.
Every time the page posts back, it is essentially starting over from scratch - anything initialized to 0, for example, will be zero again. This is because the server doesn't know anything about the last time the page ran - all it knows is you clicked a button which submits a form to that page, so it creates another instance of the page and starts again.
If you need to persist a value across postbacks, the standard method is to use ViewState:
Public Property MyCounter() As Integer
Get
Dim val As Object = ViewState("MyCounter")
Return If(val IsNot Nothing, CInt(val), 0)
End Get
Set(ByVal value As Integer)
ViewState("MyCounter") = value
End Set
End Property
It's also possible to use Session, which will persist the value across all pages and requests for the life of the user's session. For that to work, you can use the same sample above, replacing ViewState with Session.
Put this code in your Button Click Event
int count=0;
count++;
ViewState["count"] = Convert.ToInt32(ViewState["count"]) + count;
Label1.Text = ViewState["count"].ToString();
#Rex M's suggestion for using Viewstate is good.
If the counter is not sensitive information or something you're worried about someone tampering with., here's an easier idea:
You can also use an <asp:HiddenField> and store the value there. Then it will persist between postbacks and you can increment it each time..
Her's another method that doesn't use hidden field, viewstate, session or cache
Probably not something very 'safe' but probably saves you some time.
Assuming initial Label1.Text = 0
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles Button1.Click
Label1.Text = (Integer.Parse(Label1.Text) + 1).ToString()
end Sub
your page class gets recreated on each request... so myCounter won't exist the next time.
you can either
make myCounter static (not a great idea)
put it in the Application, Session, or Cache collection
depends on what you're trying to do
You can use view count :---
Code on event of button_click..
ViewState["count"] = Convert.ToInt32(ViewState["count"])+1;
Label2.Text = "This button has been clicked " + ViewState["count"].ToString() + " times";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["Count"] = 0;
}
}
protected void btnCount_Click(object sender, EventArgs e)
{
ViewState["Count"] = (int)(ViewState["Count"]) + 1;
lblCount.Text = "Page Visited " +ViewState["Count"].ToString() +" times !";
//Response.Write(ViewState["Count"].ToString());
}
I have a wizard control in my asp.net 2.0 project, and it contains a few steps. The second step has a textbox with a standard requiredfieldvalidator control attached to it. When the user clicks Next and the box is empty, the validator complains, all is normal.
However, when the user uses the sidebar steps to skip to the next-to-last step, and clicks Finish, the validator is not fired, and the textbox is empty. In my backend, I have this:
Protected Sub wizard_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles wizard.FinishButtonClick
If Page.IsValid Then
...
Else
lblError.Text = "You missed some fields, please return and enter them"
e.Cancel = True
End If
End Sub
(lblError is a label on the complete page, but that's not really the issue)
This code does not work...
What is a good solution to this problem? Remove the sidebar and just not use it? Hardly the nicest solution...
It's far from perfect, but I'm now using this as an answer:
Protected Sub wzrdAddEvent_SideBarButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles wzrdAddEvent.SideBarButtonClick
If e.NextStepIndex > (e.CurrentStepIndex + 1) Then
e.Cancel = True
End If
End Sub
"if using the sidebar steps, only allow one step forward at the most"