How to access page controls from master page? - c#

I am aware that many of the content pages will create textBox controls with lets say txtCustomerName. And if this is found I need to update the value from session. In this particular case I can not move these controls to master page.
How do you access page controls from master page. And in which event of page life cycle should we attempt to do this ?

You can find in any Event you would like to, like in this example I am showing you on Button Click Event
protected void Button1_Click(object sender, EventArgs e)
{
TextBox TextBox1 = ContentPlaceHolder1.FindControl("TextBox1") as TextBox;
if (TextBox1 != null)
{
Label1.Text = TextBox1.Text;
}
}

Related

Why does my dynamically created user control doesn't fire button click event

i have a problem with user control.
i create it dynamically on my aspx page after clicking on a button:
protected void btnAddRules_Click(object sender, EventArgs e)
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
MyPanel.Controls.Add(Control);
}
when i click on a button of my user control, the button event wont fire and the user control will disappear. here is the button event:
protected void btnAdd_Click1(object sender, EventArgs e)
{
WowzaRule rule = GetRuleFromGUI();
RuleList.Add(rule);
//Session["RuleList"] = RuleList;
//List<WowzaRule> test = new List<WowzaRule>();
SaveToXMLFiles(txtdbnum.Text, RuleList);
}
i understand that after pressing the button on mypage the usercontrol is released and if its not created on pag_init or page Load it wont stay, but i need to create it on my button click event and find a way for it not to disapper.
thanks in advance, Daniel
You might have to add an event handler that it can fire the click event and call your delegate
Control.Click += btnAdd_Click1;
Dynamically created controls, once added, have to be on a page on every page load in order to work correctly. What happens in your case:
RuleProperty is added after the button click
Page loads with this control
User clicks on the button within RuleProperty
Control is not added to the control tree during the page load (corresponding code is only in the button click handler, and that button was not clicked)
ASP.NET does not know which control triggered the event, so the event is not processed
To go around this issue you need to add you control on every page loading, for example using some flag stored in ViewState:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["AddRuleProperty"] != null && (bool)ViewState["AddRuleProperty"])
{
AddRulePropertyControl();
}
}
protected void btnAddRules_Click(object sender, EventArgs e)
{
AddRulePropertyControl();
ViewState["AddRuleProperty"] = true;
}
private void AddRulePropertyControl()
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
MyPanel.Controls.Add(Control);
}
Update.
If you want to remove the control from the page later on in the control's click handler, you need to remove corresponding ViewState key. This is not possible from the control directly, since property Page.ViewState is protected, and also this would have created an unwanted dependency.
What seems as the right way to do this is to subscribe to the very same event from the Page (you might need to make this event visible from the controller) and reset the key in there. Like this:
private void AddRulePropertyControl()
{
RuleProperty Control = (RuleProperty)LoadControl("RuleProperty.ascx");
Control.ButtonClick += RuleProperty_ButtonClick;
MyPanel.Controls.Add(Control);
}
private void RuleProperty_ButtonClick()
{
ViewState["AddRuleProperty"] = false;
}
Please note that event name here is not real, this is just a sketch of what can be done.

button action not firing

I have a web form which dynamically loads controls upon selection in combobox(devexpress). I have the following code on main form
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
if (Session["_active_control"] != null)//persist control on postbacks
{
Control cntrl = Session["_active_control"] as Control;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
protected void cmb_control_SelectedIndexChanged(object sender, EventArgs e)
{
Control cntrl= Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
Session["_active_control"] = cntrl;
}
also I have a user control having three Textboxes and a button having code
protected void btn_save_Click(object sender, EventArgs e)
{
lbl.Text = ASPxTextBox1.Text + "<br>" + ASPxTextBox2.Text + "<br>" + ASPxTextBox3.Text;
}
My problem is that the save button of user control is not firing if i load it dynamically (I have checked using breakpoints and also the code shown above. however it runs smoothly if I use it statically.(i.e. by dragging in design mode)
You are right that you have to persist the control across postbacks.
However the Page Load event is too late to add back your controls. Do this on the Init event of your page and you should be good. To receive a postback event, the control should be present when ProcessPostData(called before PreLoad) is called.
Also for textboxes you will want to receive the values entered by the user. This too happens on ProcessPostData, if you add you control after that, you will not receive the values entered by the user.
Refer: ASP.NET Page Life Cycle
hey i found the solution
instead on creating the controls in combobox_selectedindexchanged i put my control creation code on Pageload based in combobox.selectedindex i.e.
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (cmb_control.SelectedItem != null)
{
Control cntrl = Page.LoadControl("~/" + cmb_control.SelectedItem.Value);
cntrl.ID = "_new_ctrl" + cmb_control.SelectedItem.Value;
pnl_main.Controls.Clear();
pnl_main.Controls.Add(cntrl);
}
}
see Button click event not firing within use control in ASP .Net

Page lifecycle question

I am using a DropDown menu and an UpdatePanel to filter out a DataGrid. The DataGrid has buttons which redirect to a different page. When I hit the back button or a link on top of the other page, it redirects me to the page with the DropDown as it should...but it gets rid of the DataGrid data and I have to make a selection from the DropDown again. Is there a way to make sure that the DropDown selection is remembered when both the link is pressed and the back button selected? Thanks for your help!
The easiest thing to do in this case is to save the dropdown selection in Session collection
and on page load, check to see if there is a saved selection and use it to reapply the selection.
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SavedSelection"] = DropDownList1.SelectedIndex;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Session["SavedSelection"] != null)
{
int selectedIndex = (int) Session["SavedSelection"];
DropDownList1.SelectedIndex = selectedIndex;
}
}

Why ASCx disappear if clicking button to Save?

i added ascx control in tab control with C# codes. if you click any tabs. ASCX control load. tab control in update pane. Alos ASCX control includes button if you click button you can add some value to database but ASCX disappear. i think that it is reloaded. How can i solve it?
i loaded ascx control if i click tab control. i have a button on ASCX. i clicked button ASCX disapper..
protected void ASPxPageControl1_ActiveTabChanged(object source,
DevExpress.Web.ASPxTabControl.TabControlEventArgs e)
{
if (ASPxPageControl1.ActiveTabPage.Name == "Ali Sp. Reqs")
PhAliSpReqs.Controls.Add(UserControlHelper.LoadControl(this.Page, "~/EngWebUserControl/AliSpReqs.ascx"));
else if (ASPxPageControl1.ActiveTabPage.Name == "Test")
PhTest.Controls.Add(UserControlHelper.LoadControl(this.Page, "~/EngWebUserControl/Test.ascx"));
ASCX:
public partial class Test : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Button1_Click(object sender, EventArgs e)
{
if (txtTest.Text != String.Empty)
{
Label1.Text = "Hello!";
}
else
Label1.Text = "Error";
}
}
if i clicked tab EVERY THING IS GOOD. But click button on ascx. ASCx control disappear. How can i solve it!!!
If you add controls programmatically in code, every post-back operation needs to re-create the same controls (e.g. during Page_Load) to process the post-back event (in your case, the Save button)
Dynamically added controls have no object reference variable in the codebehind class. They appear only in the control collection of the containing control, i.e. the Page.Controls collection. When the page is posted back to the server as a result of user interaction a new instance of the codebehind class is instantiated, and all the variables of the class is set with values from the ViewState. see here

get submit button id

Inside asp.net form I have few dynamically generated buttons, all of this buttons submit a form, is there a way to get which button was submit the form in page load event?
The sender argument to the handler contains a reference to the control which raised the event.
private void MyClickEventHandler(object sender, EventArgs e)
{
Button theButton = (Button)sender;
...
}
Edit: Wait, in the Load event? That's a little tricker. One thing I can think of is this: The Request's Form collection will contain a key/value for the submitting button, but not for the others. So you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
Button theButton = null;
if (Request.Form.AllKeys.Contains("button1"))
theButton = button1;
else if (Request.Form.AllKeys.Contains("button2"))
theButton = button2;
...
}
Not very elegant, but you get the idea..
protected void Page_Load(object sender, EventArgs e) {
string id = "";
foreach (string key in Request.Params.AllKeys) {
if (!String.IsNullOrEmpty(Request.Params[key]) && Request.Params[key].Equals("Click"))
id = key;
}
if (!String.IsNullOrEmpty(id)) {
Control myControl = FindControl(id);
// Some code with myControl
}
}
This won't work if your code is inside a user control:
Request.Form.AllKeys.Contains("btnSave") ...
Instead you can try this:
if (Request.Form.AllKeys.Where(p => p.Contains("btnSave")).Count() > 0)
{
// btnSave was clicked, your logic here
}
You could try:
if (this.Page.Request.Form[this.btnSave.ClientID.Replace("_", "$")] != null) {
}
please try this code in page load event
string eventtriggeredCategory = Request.Form["ctl00$ContentPlaceHolder1$ddlCategory"];
if eventtriggeredCategory is returning any value its fired the event of ddlCategory
this is works fine for me
Thanks
Jidhu
Request.Form["__EVENTTARGET"] will give you the button that fired the postback
Use CommandArgument property to determine which button submits the form.
Edit : I just realized, you said you need this at PageLoad, this works only for Click server side event, not for PageLoad.

Categories

Resources