I am having some trouble understanding the impact of setting checkbox visibility on the checked state at various stages in the page life cycle.
Given below is a sample code for a dynamically created checkbox.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
check = new CheckBox();
check.AutoPostBack = true;
check.Text = "checkbox1";
check.ToolTip = "tooltip for checkbox1";
check.CheckedChanged += new EventHandler(check_CheckedChanged);
this.Form.Controls.Add(check);
Button btn = new Button();
btn.Text = "click me";
btn.Click += new EventHandler(btn_Click);
this.Form.Controls.Add(btn);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
check.Checked = true;
check.Text = "text reassigned.";
check.ToolTip = "tooltip reassigned";
}
}
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
check.Visible = false;
}
The issue here is, when a postback occurs (I click on the button), then I notice in the Page_load event, the checkbox maintains the viewstate of the tooltip and text. However the checked state is changed to false and it fires a CheckedChanged event. Why is the behavior so?
Also, if I set the visibility of the checkbox in either PageLoad() or the OnPreRender() event, the checked state of the checkbox is maintained across postbacks and does not fire a CheckedChanged event.
I'm just curious as to what happens differently when the visibility is changed in the OnPreRenderComplete event so as to have the checkbox default to an unchecked state.
Well I have marked my last answer for deletion, as I didn't understand the question properly.
Well the things you are doing are:
You added the checkbox at runtime in Init event on server side.
Then in page load you set its value to true in the Not Post Back check.
Then you set its visibility to false in OnPreRenderComplete event
When you set the visibility to false on server side, the control is not generated on client side (you can check it by viewing the page source), as control is not created on client side so when you post back the page, the checkbox is created in page init and as it was not on client side so dot net doesn't know about its last value, so you get false for the check box.
If you need to check it more further, change your OnPreRenderComplete event as:
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
//check.Visible = false;
check.Style.Add("display", "none");
}
By above line, the style is being added to the control, so the control is generated on client side but is not visible and you will get its value during the post back.
Related
I have dynamically generated checkboxes and having EventHandler which takes care about check change of any of the checkbox. The issue is that if i uncheck any of the checkbox, it gets all other checkbox as sender and checkchange is called according to number of checkboxes number of times. If there are 3 checkboxes and 1 is unchecked than checkchange event handler is called 2 times. I dont understand what is happening.
CheckBox chkbox;
panelDynamicCheckbox.Controls.Clear();
foreach(string product in products)
{
chkbox = new CheckBox();
chkbox.ID = product;
chkbox.Text = product;
chkbox.AutoPostBack = true;
chkbox.CheckedChanged += new EventHandler(this.CheckChanged);
panelDynamicCheckbox.Controls.Add(chkbox);
}
protected void CheckChanged(object sender, EventArgs e)
{
CheckBox checkbox = (CheckBox)sender;
}
Ensure the code to add the dynamic checkbox and especially the event handler specification is done in the OnInit method in the page life-cycle. If you don't do this, these sort of unpredictable state behavior can be seen.
When I click btnGDynamicCont I want to load the first set of controls, then on each further click of that button, add a new control (textbox) alongside the other ones, so each time it is clicked I am adding a new textbox across state.
Do you know where I should add the creation of the new textbox in order to keep it after each postback?
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true")
GenerateDynamicControls();
}
public void GenerateDynamicControls()
{
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
txtDynamic.Text = "Dynamic TextBox";
Page.Form.Controls.Add(txtDynamic);
TextBox txtDynamic2 = new TextBox();
txtDynamic2.ID = "txtDynamic2";
txtDynamic2.Text = "Dynamic Textbox";
Page.Form.Controls.Add(txtDynamic2);
}
protected void btnGDynamicCont_Click1(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
GenerateDynamicControls();
ViewState["Generated"] = "true";
}
else
{
Response.Write("<h2>Controls are already exist in page</h2>");
}
}
}
}
Dynamic controls are usually recreated at the Page_Load method. For more information, please refer to the Dynamically Created Controls in ASP.NET article.
You can refer the below link where a very similar issue is addressed.
unable to add more than one server control dynamically in asp.net
Everytime a postback happens, you should recreate the already existing controls(dynamically added) in your page_load event and the new controls are to be created in the button_click event.
Use some logic to generate ids for the controls for the viewstate to be maintained. VIEWSTATE will be taken care automatically if the ids of the controls generated before and after postback are the same.
One way to keep track of the number of textboxes is to store the count in session.
I'm trying to have a user/admin scenario for editing a formview. What I have is the Edit buttons in the formview be visible=true by default. Then I use a statement which says if the role is not equal to admin, then set the visibility to false for the edit button. It works like it should, when I click around, do postbacks, etc. the items stay hidden if the user is and admin...except when I use a dropdown list for filtering, which uses a statement like dataSource1.FilterExpression = ("ID=" + ddl1.SelectedValue).
Whether I set the default visibility to true or false for the formview edit linkbutton, when using the FilterExpression, it changes the visibility of what I don't want it to be. It is because the FilterExpression sets the visibility of the control to whatever the default visibility property of the control is set to.
Below is some code as an example of what I mean. Please help!
protected void Page_PreRender(object sender, EventArgs e)
{
string role;
role = "client";
LinkButton editGeneralOverview = (LinkButton)formViewGeneralOverview.FindControl("EditButton");
if (role != "admin"))
{
editGeneralOverview.Visible = false;
}
if (ddlIDFilter.SelectedValue != "-- ALL --")
{
dataSourceGeneralOverview.FilterExpression = ("ID=" + ddlIDFilter.SelectedValue);
}
You could hide it in the FormViews DataBound event:
protected void formViewGeneralOverview_DataBound(Object sender, EventArgs e)
{
LinkButton editGeneralOverview = (LinkButton)formViewGeneralOverview.FindControl("EditButton");
if (role != "admin"))
{
editGeneralOverview.Visible = false;
}
}
This way your visibility setting gets (re)applied after the FilterExpression has already taken effect.
Note: in case you do not know, you can attach this event to the FormView in the markup by setting the OnDataBound property. Like this:
<asp:FormView ID="formViewGeneralOverview"
OnDataBound="formViewGeneralOverview_DataBound"
...whatever other propeties you have >
...templates and junk...
</asp:FormView>
I am fairly new to the asp.net and experimenting with it to learn the page life cycle. Here is a problem that I have been unable to resolve for past few days.
I have a hosting page (.aspx). Then I have two user controls (.ascx). The page has a place holder control in which it loads the user controls one at a time based on the application flow. First user control is loaded on application start up. It has a "continue" button. Continue button click loads the Second user control that has two buttons - "Back" and "Submit". Obviously the "Back" button should load the first user control again and Submit button should submit the form data. Pretty simple.
The problem is that the command button event handler that I have on the second user control is not firing the first time. (I have one event handler for both buttons). The load event of the user control fires but then it ignores the button click. If I click it again, then it fires. I re-load the controls on the page in every page_load. Here is some relevent code:
AddPlayer.aspx:
protected void Page_Load(object sender, EventArgs e)
{
PlaceHolder1.Controls.Clear();
// Load the ctlInputPlayer control
Control ctlToAdd = LoadControl("ctlInputPlayer.ascx", null);
if (ctlToAdd != null)
{
_ctlInputPlayer = (ctlInputPlayer)ctlToAdd;
_ctlInputPlayer.SendPlayerData += new EventHandler(ctlInputPlayer_SendPlayerData);
PlaceHolder1.Controls.Add(_ctlInputPlayer);
}
// see if there is player data available in the view State
PlayerData player = (PlayerData)ViewState["Player"];
if (player != null)
{
ctlToAdd = LoadControl("ctlPlayerInfo.ascx", player);
if (ctlToAdd != null)
{
_ctlPlayerInfo = (ctlPlayerInfo)ctlToAdd;
_ctlPlayerInfo.SubmitPlayerData += new EventHandler(ctlPlayerInfo_SubmitPlayerData);
PlaceHolder1.Controls.Clear();
PlaceHolder1.Controls.Add(_ctlPlayerInfo);
}
}
}
ctlPlayerInfo.ascx (second user control):
ctlPlayerInfo.ascx.cs
protected void CommandBtn_Click(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Submit":
//submitPlayerData will fire here
break;
case "Back":
// editplayer data will fire here
break;
}
}
protected void Page_Load(object sender, EventArgs e)
{
// load control data here....
}
The page_Load fires every time but "CommandBtn_Click" doesn't fire after the first click. I have to do it click it again. It doesn't matter which order I click the buttons.
I appreciate the help. Let me know if more details are needed. Thanks!
You should load your user controls every time in Page_Init and set the ID property.
I am using an ASP.NET AJAX-Enabled Web application (ASP.NET 2.0 and AJAX Toolkit 1.0)
that contains one button and 2 UpdatePanels (UpdatePanel_1 and UpdatePanel_2)
The button is registered with RegisterAsyncPostBackControl in the ScriptManager object
UpdatePanel_1 is in "Conditional" update mode and contains a TextBox.
UpdatePanel_2 is in "Always" update mode and contains another TextBox
When the button is pressed its handler calls UpdatePanel_1.Update() that updates the value of the TextBox based on a randomly selected value in a list;
Also the UpdatePanel_2's TextBox is being updated automatically , also without page refresh
Based on the value of a boolean ViewState variable I would also like to hide/show the UpdatePanels alternatively but
I get the error :
"Sys.InvalidOperationException: COuld not find UpdatePanel with ID 'UpdatePanel_2' (or UpdatePanel_1).
If it is being updated dynamically then it must be inside another UpdatePanel"
How can it be done without adding extra wrapping UpdatePanels?
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterAsyncPostBackControl(Button1);
if (!IsPostBack)
{
Visibility = true;
}
UpdatePanel_1.Visible = !Visibility;
UpdatePanel_2.Visible = Visibility;
Visibility = !Visibility;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Panel1.Visible)
UpdatePanel_1.Update();
}
protected bool Visibility
{
get
{
return (bool)(ViewState["Visibility"] ?? true);
}
set
{
ViewState["Visibility"] = value;
}
}
The problem is that invisible controls aren't rendered to the client. So then trying to make them visible isn't going to work because as far as the client is concerned, they don't exist.
Try using style="display:none", or use different CSS classes and styles for visible and invisible panels, rather than setting visible=false;
You can invisible, or visible controls is child of updatepanel, not invisible, visible updatepanel, I try use updatemode = conditional but error, and then I visible controls add to updatepanel. Hopy help you
Thanks everybody post