ASP .Net Gridview rowupdated - can it happen before the page load? - asp.net

Here's the scenario:
-Gridview control
-Calendar control
I only want the calendar to show if a specific item is chosen in the drop down list which is in a gridview. When the grid view row is updated I want to change whether or not the calendar is visible. The calendar's visibility only shows correctly on the next post back.

Page_Load is called before events which are called before Render. There is no reason why you couldn't, in your event, check the value of the dropdownlist and set the Calendar control visible property, this would then knock into Render.

Try adding a check of IsPostBack before setting the loading your GridView. That will prevent you from overwriting it's values.
protected void Page_Load(object sender, EventArgs e) {
if(!IsPostBack) {
/*Populate your GridView*/
}
}
protected void GridView_RowUpdated(object sender, GridViewUpdatedEventArgs e)
{
/*show your calendar here if you need to*/
if(whatever) calendar.Visible = true;
}
This should work, if it doesn't then I'd recommend putting breakpoints in your Page_Load and RowUpdated methods and stepping through it, preferrably with a Watch on the gridview's datasource (it'll go red if it's changed) and a watch on calendar.Visible, to help you see if something has changed.
For the record, control events like OnRowUpdated will never fire before Page_Load unless explicitly called for some reason. Chances are you're just doing something where it's not updating the content of the GridView before it gets to the RowUpdated method, or it's overwriting the data in the GridView due to a lack of !IsPostBack check.

Related

CheckBoxList is not firing when uncheck last item in Formview Edit Mode

CheckBoxList don't fire under the following condition
CheckBoxList has been set to AutoPostBack.
It fired When checked or unchecked with at least one item left checked.
It didn't fired when unchecked and no single checked item left.
it is wrapped in update panel condition mode set to alway.
Question: Is there anyway to make it fire under these conditions ?
Edit 1
Add More Information
I have test on blank project, both on update panel and outside updatepanel work
I have realized that checkboxlist is put on FormView in EditMode too, this might be the cause of error
I have tried moving checkboxlist outside of formview and it worked fined now, i have to figure out how to make it works outside formview too.
After struggling to find a real solution, I have given up and came up with the following workaround.
I have use jquery to force postback"
$("#cblRoomType").live('click',
function ForcePostBack()
{
__doPostBack('<%= cblRoomType.ClientID %>', '');
}
);
Then i have set an event on Page_Load instead.
protected void Page_Load(object sender, EventArgs e)
{
if (Master.ScriptManager.AsyncPostBackSourceElementID == cblRoomType.ClientID)
{
RefreshPromotionRoomType();
}
// Other Code
}

ASP.NET: Postback processed without events being fired

I have a GridView with dynamically created image buttons that should fire command events when clicked. The event handling basically works, except for the very first time a button is clicked. Then, the postback is processed, but the event is not fired.
I have tried to debug this, and it seems to me, that the code executed before and after the first click is exactly the same as for any other clicks. (With the exception that in the first click, the event handler is not called.)
There is some peculiarity in that: The buttons which fire the event are created dynamically through databinding, i.e. databinding must be carried out twice in the page lifecycle: Once on load, in order to make the buttons exist (otherwise, events could not be handled at all), and once before rendering in order to display the new data after the events have been processed.
I have read these posts but they wouldn't match my situation:
ASP.NET LinkButton OnClick Event Is Not Working On Home Page,
LinkButton not firing on production server,
ASP.NET Click() event doesn't fire on second postback
To the details:
The GridView contains image buttons in each row. The images of the buttons are databound. The rows are generated by GridView.DataBind(). To achieve this, I have used the TemplateField with a custom ItemTemplate implementation. The ItemTemplate's InstantiateIn method creates the ImageButton and assigns it the according event handler. Further, the image's DataBinding event is assigned a handler that retrieves the appropriate image based on the respective row's data.
The GridView is placed on a UserControl. The UserControl defines the event handlers for the GridView's events. The code roughly looks as follows:
private DataTable dataTable = new DataTable();
protected SPGridView grid;
protected override void OnLoad(EventArgs e)
{
DoDataBind(); // Creates the grid. This is essential in order for postback events to work.
}
protected override void Render(HtmlTextWriter writer)
{
DoDataBind();
base.Render(writer); // Renews the grid according to the latest changes
}
void ReadButton_Command(object sender, CommandEventArgs e)
{
ImageButton button = (ImageButton)sender;
GridViewRow viewRow = (GridViewRow)button.NamingContainer;
int rowIndex = viewRow.RowIndex;
// rowIndex is used to identify the row in which the button was clicked,
// since the control.ID is equal for all rows.
// [... some code to process the event ...]
}
private void DoDataBind()
{
// [... Some code to fill the dataTable ...]
grid.AutoGenerateColumns = false;
grid.Columns.Clear();
TemplateField templateField = new TemplateField();
templateField.HeaderText = "";
templateField.ItemTemplate = new MyItemTemplate(new CommandEventHandler(ReadButton_Command));
grid.Columns.Add(templateField);
grid.DataSource = this.dataTable.DefaultView;
grid.DataBind();
}
private class MyItemTemplate : ITemplate
{
private CommandEventHandler commandEventHandler;
public MyItemTemplate(CommandEventHandler commandEventHandler)
{
this.commandEventHandler = commandEventHandler;
}
public void InstantiateIn(Control container)
{
ImageButton imageButton = new ImageButton();
imageButton.ID = "btnRead";
imageButton.Command += commandEventHandler;
imageButton.DataBinding += new EventHandler(imageButton_DataBinding);
container.Controls.Add(imageButton);
}
void imageButton_DataBinding(object sender, EventArgs e)
{
// Code to get image URL
}
}
Just to repeat: At each lifecycle, first the OnLoad is executed, which generates the Grid with the ImageButtons. Then, the events are processed. Since the buttons are there, the events usually work. Afterwards, Render is called, which generates the Grid from scratch based upon the new data. This always works, except for the very first time the user clicks on an image button, although I have asserted that the grid and image buttons are also generated when the page is sent to the user for the first time.
Hope that someone can help me understand this or tell me a better solution for my situation.
A couple problems here. Number one, there is no IsPostBack check, which means you're databinding on every load... this is bound to cause some problems, including events not firing. Second, you are calling DoDataBind() twice on every load because you're calling it in OnLoad and Render. Why?
Bind the data ONCE... and then again in reaction to events (if needed).
Other issue... don't bind events to ImageButton in the template fields. This is generally not going to work. Use the ItemCommand event and CommandName/CommandArgument values.
Finally... one last question for you... have you done a comparison (windiff or other tool) on the HTML rendered by the entire page on the first load, and then subsequent loads? Are they EXACTLY the same? Or is there a slight difference... in a control name or PostBack reference?
Well I think the event dispatching happens after page load. In this case, its going to try to run against the controls created by your first data-binding attempt. This controls will have different IDs than when they are recreated later. I'd guess ASP.NET is trying to map the incoming events to a control, not finding a control, and then thats it.
I recommend taking captures of what is in the actual post.
ASP.NET is pretty crummy when it comes to event binding and dynamically created controls. Have fun.
Since in my opinion this is a partial answer, I re-post it this way:
If I use normal Buttons instead of ImageButtons (in the exact same place, i.e. still using MyItemTemplate but instantiating Button instead of ImageButton in "InstantiateIn", it works fine.
If I assert that DoDataBind() is always executed twice before sending the content to the client, it works fine with ImageButtons.
Still puzzled, but whatever...

asp.net: How to get a button to affect the page contents

In Page_Load I populate an asp:Table with a grid of images. I have a button that when pressed I would like it to repopulate the page with different images.
However it appears that when the button is pressed Page_Load is called again, followed by the script specified by the button. I thought that I could simply set a variable in the button script which is checked during Page_Load, but this will not work.
What is the most asp.netish way to approach this? Should I be populating my table somewhere other than in Page_Load, or should my button be doing something different?
Your button event gets called after page load. As such, you should put your button code in there.
I'm not terribly sure why you'd try to stuff all of your event code into Page_Load, but it's best to keep it separated.
GOOD
protected void Page_Load(object sender, EventArgs e)
{
MethodThatDynamicallyCreatesControls();
}
protected void MyImage_Click(object sender, EventArgs e)
{
MyImage.Property = newValue;
MyImage2.Property = newValue2;
PopulateTables(newValues);
}
BAD
protected void PageLoad(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
//Check to see if "MyButton" is in the Request
// if it is, it's the button that was clicked
if (Request["MyButton"])
{
MyImage.Property = newValue;
MyImage2.Property = newValue;
PopulateTables(newValues);
}
}
}
As rick said, it's all a matter of understanding the postback.
page_load gets fired every time the page is refreshed. however in many cases, you only want certain things to happen on the first time a page is loaded. in your case, you want the default images to load. by putting all 'one time' events for a page load in a
if (!Page.IsPostback )
{
}
it will only fire on the first time the page is loaded. this is what you want to load your first set of images.
Then in your button click event (which triggers a postback), the code within the if statement will not execute again. and you can load your second set of images in your button's event handler.
That button you're using should call a method in your code behind,so you can know that the button is was clicked, ex:
protected void Important_ButtonClicked(Object sender, EventArgs e)
{
//do what I want to do
}
<asp:Button id="Button1"
Text="MakeChanges"
OnClick="Important_ButtonClicked"
runat="server"/>
Actually I understand what your problem is now, seems like you just have values being set in your page load with no condition check in you page load, so every time you have a postback it refreshes the page to original state, the reason for that is because everytime you trigger a refresh(postback) on the page, the pageload method is invoked, so you need to set original setting in your page load,but have them in the condition, as
if(!Page.Postback) which gets triggered the first time you visit this page. Which means this is where your defaults go and if(Page.Postback) is where your always true things should go. ex:
protected void Page_Load()
{
// this is where I want things to always happen whenever the page is loaded
//for example, no matter what happens I want a certain image in the background
if(!Page.Postback)
{
//set my values for the first and only time
}
else //hint Page.Postback
{
//you can play with the page here to make necessary changes
//but Button click method will still be invoke so thats where button click
//changes should be made
}
}
A PostBack happend when the page is reload. The first page load, Page.IsPostBack has value false. When an event happend, Page.IsPostBack has value true.
So doing the thing like this will definitely works
void Page_Load()
{
if (!Page.IsPostBack)
{
//do your first time binding data
}
How to: Create Event Handlers in ASP.NET Web Pages
EDIT:
Your state change events are not going to fire correctly if you re-bind controls(ie:DropDownList) data on every postback.
void Page_Load()
{
if (!IsPostBack)
{
//load your data
}
}

My code says a checkbox isn't checked when it is... ASP.NET

I have some checkboxes on a page. I get them using FindControl() in an UpdatePanel after pressing a button trigger, but the checked value is wrong. How can I get the correct checked value?
If you have any code that sets the values of the checkboxes on your page, make sure it isn't executing on postbacks, like this:
protected void Page_Load(object sender, EventArgs e) {
// Only set the checkboxes on GETs, not on POSTs
if (! this.IsPostBack) {
this.EmailMeUpdatesCheckbox.Value = false;
}
}
Actions triggered within UpdatePanels still go through the page lifecycle (which is why you have access to all your Page's state), so it may be clearing the user's selections before getting to the code in which you examine the checkbox values.

Postback destroys user controls in my GridView columns

I have a ASP.NET GridView that uses template columns and user controls to allow me to dynamically construct the datagrid. Now I'm implementing the event handler for inserting a row. To do that, I create an array of default values and add it to the data table which is acting as a data source. However, when my OnLoad event is fired on postback, all my template columns no longer have the user controls. My gridview ends up just being all blank with nothing in it and my button column disappears as well (which contains the add row, delete row and save buttons).
My row add event just does this:
public void AddDataGridRow()
{
List<object> defRow = new List<object>();
for (int i = 0; i < fieldNames.Count; i++)
{
defRow.Add(GetDefaultValueFromDBType(types[i]));
}
dt.Rows.Add(defRow);
}
It is fired from a button in a user control that's implement like this:
protected void Button1_Click(object sender, EventArgs e)
{
((Scoresheet)(this.Page)).AddDataGridRow();
}
My on load event does a bunch of stuff on first run to set the GridView up but I don't run that again by using the IsPostBack property to tell.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Initialize();
}
Anyone have any hints as to why my user controls are vanishing?
You have to add the controls to the grid on every page_load, not just if it's (!Postback)
Do you have the EnableViewState=true on the usercontrols and the GridView?
Is the AddDataGridRow() method called by Initialize()? You basically have two options:
Bind the grid on every postback and do not use viewstate (performace loss)
Bind the Grid only the first time (if (!IsPostBack)), and make sure that your user controls keep their viewstate.
From your code, it is not clear whether the user controls keep viewstate and what they have in them. It is not even clear what is the execution order of the methods you've shown. There is no binding logic, so even if you keep adding rows, the grid may still not be bound. Please elaborate a bit and show the whole page codebehind.

Resources