I have a foreach loop in the Page_Load method of my one page to determine whether to Enable a button or not.
Code:
foreach (var class in classes)
{
for (var i = studentsList.Count - 1; i >= 0; i--)
{
if (studentsList[i].Id == class.student_id)
studenstList.Remove(studentsList[i]);
}
}
if (studentsList.Count == 0)
{
button1.Enabled = false;
button1.Text = "a";
}
else
{
button1.Enabled = true;
button1.Text = "b";
}
if (Page.IsPostBack) { return; }
The issue:
The value of studentsList.Count is lagging behind by a postback. If after the loop it should be 1, it only has the value of 1 at the next postback. I've debugged to confirm this is the case.
You can move this foreach loop to the Page_PreLoad method and give it a try.
Here anof life cycle of an ASP.NET page: http://msdn.microsoft.com/en-us/library/ms178472.aspx#lifecycle_events
I guess the student list is updated by clicking a button on the page.
Put the code that enables button1 on the button_click event of that button.
Does the button press edit students list? If so, the code for the button press will be fired after the Page_Load code.
Your problem is that you should wait for a corresponding event and write this logic in that event handler. For clarity, page load happens earlier than control events.
Related
I am trying to get this sample to work
Get Selected Row (on server)
but for me the SelectedRow property is always empty.
The only difference being that I am using the Page_load event to populate my grid.
When i press a button on my form, it does a postback, and repopulates the grid losing the row selection.
sample code:
if (!Page.IsPostBack )
{
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
GRDUsers.DataBind();
}
protected void btnEdit_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(GRDUsers.SelectedRow))
{
lblError.Visible = true;
}
else
{
Response.Redirect(string.Format("~/Manage/EditUserRoles.aspx?username={0}",GRDUsers.SelectedRow));
}
}
I Have also noticed that on button click, my Page Load fires twice (1st time postback is true, 2nd time it is false) According to jqgrid posts this is intentional. but i think this might be causing my grief.
You always must set the DataSource because is not saved on ViewState or anywhere else. So the code must be as:
UserBusinessObject userBO = new UserBusinessObject();
GRDUsers.DataSource = userBO.GetUsersbyProfileID(SessionFacade.Id);
if (!Page.IsPostBack )
{
GRDUsers.DataBind();
}
working with the guys at JQGrid, we have resolved the problem. It is a bug in their grid that has been fixed in v4.5.0.0
see here for details
i can confirm that this fixes the bug, and all is right with the world again
I'm building an ASP.NET application. I'm using a ListView to show some Entities however my listview doesn't have items on the first pass. I mean, they show up on the page, but this code only works when I refresh the page:
protected void Page_Load(object sender, EventArgs e)
{
fillFeatures();
}
private void fillFeatures()
{
using (Entities myEntities = new Entities())
{
System.Diagnostics.Debug.Write("Filling features.. \n");
foreach (ListViewItem item in ListView1.Items)
{
System.Diagnostics.Debug.Write("FOR \n");
CheckBox checkbox = (CheckBox)item.FindControl("Checkbox");
TextBox description = (TextBox)item.FindControl("descriptionTextbox");
//Try to get an existing relation
int featureId = Int32.Parse(((Label)item.FindControl("idLabel")).Text);
PlaceHasFeature phf = (from p in myEntities.PlaceHasFeature
where p.place_id == placeId && p.feature_id == featureId
select p).SingleOrDefault();
if (phf != null)
{
System.Diagnostics.Debug.Write("Checking " + phf.Feature.name + "\n");
//Relation exists
checkbox.Checked = true;
description.Text = phf.description;
}
else
{
System.Diagnostics.Debug.Write("Didn't find relation for " + featureId + "\n");
}
}
}
}
Console output:
When I open the link: Filling features...
After refresh: Filling features... FOR FOR FOR (...)
Anyone knows the cause of this?
I suspect the issue is due to the ASP.NET Page Life Cycle, where the page load event occurs before the individual controls load event:
The Page object calls the OnLoad method on the Page object, and then
recursively does the same for each child control until the page and
all controls are loaded. The Load event of individual controls occurs
after the Load event of the page.
I believe you have a couple of options. Move the fillFeatures method to the Page.LoadComplete Event:
The LoadComplete event occurs after all postback data and view-state
data is loaded into the page and after the OnLoad method has been
called for all controls on the page.
Or move the fillFeatures method to the ListBox's DataBound Event. Though I would suspect that the Page.LoadComplete Event is really the better of the two options.
Is there a way to determine if an <asp:UpdatePanel /> has performed an Ajax postback similar to how we can use...
if(!Page.IsPostBack) { ...snip }
... to determine if a postback from a button submit is taking place.
I'm trying to detect Ajax requests from jQuery, but it's picking up UpdatePanel requests as well which I want to exclude eg...
if (Request.IsAjaxRequest() && !Page.IsUpdatePanelPostback)
{
// Deal with jQuery Ajax
}
You can check whether the postback was asynchronous and whether it was issued by an update panel looking at these properties:
ScriptManager.GetCurrent(Page).IsInAsyncPostback
ScriptManager.GetCurrent(Page).AsyncPostbackSourceElementID
I don't know if this will work any better than your solution, but have you tried?:
if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
Control ctrl = GetControlThatCausedPostBack(Page);
if (ctrl is UpdatePanel)
{
//handle updatepanel postback
}
}
private Control GetControlThatCausedPostBack(Page page)
{
//initialize a control and set it to null
Control ctrl = null;
//get the event target name and find the control
string ctrlName = Page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(ctrlName))
ctrl = page.FindControl(ctrlName);
//return the control to the calling method
return ctrl;
}
Try out following:
var controlName = Page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(controlName))
{
// Use FindControl(controlName) to see whether
// control is of UpdatePanel type
}
Helpful links:
ASP.NET: Recursive FindControl & Extension Methods
I am working with the .Net List view along with a data pager to enable pagination for a list view.
I am able to set the pagination working perfectly for the list view but I wish to have a method being called when ever the user clicks on any of the page numbers in the data pager.
I want to perform some operation whenever the page number is called. I guess there is no onclick event, so is there any other way by which this is possible.
Thanks
you can set it as imagebutton or linkbutton.
I have piece of code.. you just need to implement it.
you can set link and click event.
foreach (DataPagerFieldItem dpfItem in dtpPaging.Controls)
{
foreach (Control cPagerControls in dpfItem.Controls)
{
if (cPagerControls is ImageButton)
{
ImageButton imgNavigation = cPagerControls as ImageButton;
imgNavigation.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
imgNavigation.Click += new ImageClickEventHandler(imgNavigation_Click);
}
if (cPagerControls is LinkButton)
{
LinkButton lnkNumbers = cPagerControls as LinkButton;
lnkNumbers.PostBackUrl = CommonLogic.GetFormattedURL(strPageUrl);
lnkNumbers.Click += new EventHandler(lnkNumbers_Click);
}
}
}
You can bind a handler to the OnPagePropertiesChanging Event of the List View. A PagePropertiesChangingEventArgs object is passed to the handler as argument which contains MaximumRows and StartRowIndex properties. You can use these to calculate the current page number. It is very easy and requires no code-behind event binding as the solution proposed by sikender.
Let me start with pointing out, this is not an easy question to answer. At least it's dead near impossible to find the answer.
In an UpdatePanel I dynamically add some controls to a panel control of mine.
List<Showing> showings = cBLL.GetShowings(tenant.Id);
int j = 1;
foreach(Showing showing in showings)
{
UserControl uc = (UserControl)Page.LoadControl("Controls/BookShowing.ascx");
uc.ID = "showing_" + j;
uc.Visible = true;
((BookShowing)uc).SetShowing(showing);
pnl_showings.Controls.Add(uc);
j++;
}
This all takes place in a button event fired from a control asychrone.
Below these fields I add in the code shown above I have a button. The button is also placed in the updatepanel. This button is called: btn_editShowings
Now when I come to the btn_editShowings_Click event handler, my dynamic added controls does not exist anymore. I have also tried catching them in the OnInit but they dont exist there either.
How the F... is it ever possible to obtains data from the dynamic added controls???
Is there anyway, and I don't care how lousy it performs or anything, to solve this?
UPDATE:
I have now tried to do the following which should work as Init fires before LoadViewState from what I have read.
I add some controls dynamic in a Button event
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = j; i < showno + 4; i++)
{
UserControl uc = (UserControl)Page.LoadControl("Controls/BookShowing.ascx");
uc.ID = "showing_" + i;
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
pnl_showings.Controls.Add(uc);
}
UpdatePanel1.Update();
}
And I have done the same thing in my init function:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Session["ShowingsCount"] != null)
{
int noOfUCs = (int)Session["ShowingsCount"];
for (int i = 1; i < noOfUCs; i++)
{
UserControl uc = (UserControl)Page.LoadControl("Controls/BookShowing.ascx");
uc.ID = "showing_" + i;
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
pnl_showings.Controls.Add(uc);
}
UpdatePanel1.Update();
}
}
But when I try this:
FindControl("showing_1").Visible = false;
I get a null reference exception.
Best Regards
The Real Napster, troubled once again.
When you add the controls the first time, keep track of the number of controls you need to recreate in the viewstate.
On every post-back after that make sure you add that number of controls back onto the page with the same IDs in the LoadViewState method.
The key is that you always have to add dynamically created controls to the page every post-back and you have to do it before the viewstate loads in order for the controls to get their form-posted values loaded back into them.
BookShowing bs = (BookShowing)UpdatePanel1.FindControl("showing_" + i);
Was the solution, The OnInit override did actually work, it was me fetching the usercontrol the wrong way.
Closed.