Accessing Other Page Controls From This Page - c#

Page 1 - Ticket.aspx, DropDownList1, ModalPopUpextender with id mpe
Page 2 - Customer.aspx, btnSave
The index change event of dropdown will pop up mpe which has an iframe. This iframe loads Customer.aspx.
I am trying to access page1 controls in the button click event, but unable to.
Customer.aspx.cs:
protected void btnSave_Click()
{
Ticket page = new Ticket();
ModalPopUpExtender mpe = (ModalPopUpExtender)page.FindControl("mpe");
DropDownList ddl = (DropDownList)page.FindControl("DropDownList1");
//error here - Object reference not set to an instance
mpe.hide();
ddl.selectedindex=0;
}
Why is this not working. Using a Session variable should work right?

You may use Server.Transefer instead of Response.Redirect and then you can find the control in the current page.
Like:
TextBox tb = (TextBox)PreviousPage.FindControl("textbox1");
EDIT:
if (Page.PreviousPage != null)
{
DropDownList ddl1 =
(DropDownList)Page.PreviousPage.FindControl("DropDownList1");
if (ddl1 != null)
{
Label1.Text = ddl1.SelectedItem.Text; //your logic
}
}

What you are trying may not be doable from the server side, but it can be easily be done with a little javascript. Here is a link where you can get a working piece of code.
Hope this helps.

Related

Which event is fired on master page after content pages have rendered

I have a requirement where I need to pass the value of page title to Facebook share plugin only after the page title has been set by the content page. There are a few pages(Dynamic Data pages) where the page's title is set upon a specific control's PreRender event (I cannot change this).
If I pass the content page title on Master page's PreRenderit returns the unset value as Master page's PreRender is fired before content page's control PreRender. I tried passing the value in the master page's Unload event but it did not work! How do I achieve this?
So the question can be summarised as, perform something on master page after the content pages have performed all of their tasks and are ready to unload.
Is there a way to do this in master page itself or will I have to do this in the individual pages?
Reference: Events in ASP.NET Master and Content Pages
Dynamic Data Page:
string Location = null;
protected void DynamicFilter_PreRender(object sender, EventArgs e)
{
DynamicFilter Filter = (DynamicFilter)sender;
MetaColumn metaColumn = table.GetColumn(Filter.DataField);
QueryableFilterUserControl fuc1 = Filter.FilterTemplate as ForeignKeyFilter;
if (fuc1 != null && fuc1.FilterControl != null)
{
DropDownList ddl = fuc1.FindControl("DropDownList1") as DropDownList;
if (ddl != null)
{
if (metaColumn.DisplayName == "Location")
{
if (ddl.SelectedIndex != 0)
{
Location = ddl.SelectedItem.Text;
}
}
}
}
if (Location != null)
{
// set the page title based on the location
Page.Title = String.Format("Recent {0} Fares", Location);
}
}
This function sets the content page's(a dynamic data page) title.
Now I need to access this title on the my master page only after it has been set.
Master Page:
protected void Page_Load(object sender, EventArgs e)
{
// pass the value of page title to SocialNetworkingHelper class to do some work
SocialNetworkingHelper.SetSocialMediaMetaTag(this.Page, this.Page.Title);
}
use page unload event to perform final cleanup like closing files, releasing memory etc...if you set page title here it will not be rendered....you have to set title on control prerender event itself...

Accessing Childpage Control Value from Master Page Button Click

I have a master page with a button and i have a client page with master page reference. I would like to change the child page label values while i click the master page button. I can't change that.
Label StrHref= (Label)MainContent.FindControl("lblhead");
HiddenField StrCalId = (HiddenField)MainContent.FindControl("hf_callid");
StrHref.Text = "12345678901";
StrCalId.Value = "1395741766.47";
Try the below code on your masterPage button click event.
I have kept one button on masterpage with name as btnMaster and on child page I have put on text box and on click of MasterPage btnMaster I have used the below method.
protected void btnMaster_Click(object sender, EventArgs e)
{
var textbox = this.ContentPlaceHolder1.FindControl("txtChild") as TextBox;
textbox.Text = "Text from Master to child control";
}
Let me know if you have any issue.

Add dynamic ASP.NET controls via a DropDownList to the page

- Primary Info:
In my recent project, I need to have a page with a DropDownList with some items like 'firstName' , 'lastName' , 'Age' and etc. I want to add optional controls to the page when every item selected by user. For example when user select the 'Age' another dropdownlist created dynamically with these values : 'Less than 10'
'Between 10 and 30'
'more than 30'
Here is a button that add this user selection to listBox and let user to choice another options. (I made a query at last according to user choices and send it to db)
- What I do:
I create a dropDownList and set it's AutoPostBack property to true and adds some items in it and user must select one of those item. then I add user SelectedValue of dropDownList in a Cache variable before page post back happens:
protected void DropDownListColumnNameSelectedIndexChanged(object sender, EventArgs e)
{
Cache["SelectedKey"] = dropDownListColumnName.SelectedValue;
}
When user select an item from dropDownList *DropDownList_SelectedIndexChanged* fire, and I must create controls dynamically in a place holder:
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
- What is the problem?
When I try add new control in current Button_Click event, control added successfully to page but I can't find it by placeHolderFirstItem.Controls.Find("textBoxName") actually placeHolderFirstItem.Controls.Count is always zero. So I can't get textBoxName.Text values.
I try to google that for any solution and I found some solution that I must add controls in Page.OnInit so I add controls in overridden OnInit(e):
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
after doing this I can find "textBoxName" in placeHolderFirstItem, but it fire before DropDownList_SelectedIndexChanged !
so how can I add new controls to place holder exactly when user change the dropDownList value and how can I read new controls value?
Thanks in advance,
Mohsen.
- Updated:
Here is the better solution
(http://forums.asp.net/p/1959726/5596531.aspx?p=True&t=635244790943067485&pagenum=1)
When you are dynamically adding controls, you have to reload the controls into the control tree everytime thereafter for it to appear. With the help of viewstate, you could change your code sample to have:
ViewState("ShowTextbox") = true
And then in your init routine:
protected override void OnInit(EventArgs e)
{
if (!Page.IsPostBack) return;
if (ViewState("ShowTextBox") == true) {
var textBoxName = new TextBox
{
ID = "textBoxName",
CssClass = "str-search-textbox-highlight",
ViewStateMode = ViewStateMode.Disabled
};
placeHolderFirstItem.Controls.Add(textBoxName);
}
}
Please note it's much easier to have a control on the control tree, and then show/hide by setting Visible to true/false, because of these ASP.NET control tree issues.

Find control inside ContentPlaceHolder inside a repeater

I'm having some trouble being able to access a control inside my repeater which is found in the ContentPlaceHolder. My previous method without the master page was working fine but now that I included a master page it threw a lot of things off mainly because of the naming. Here is the code that I previously had that worked without the master page:
LinkButton button = sender as LinkButton;
// Get index of LinkButton that was clicked
int repeaterItemIndex = ((RepeaterItem)button.NamingContainer).ItemIndex;
foreach (RepeaterItem myRepeater in rptrWebsites.Items)
{
TextBox myText = myRepeater.FindControl("Web") as TextBox;
var id = myText.ClientID;
// Get just the number part of the ID
id = id.Replace("rptrWebsites_Web_","");
if (repeaterItemIndex.ToString() == id)
{
webName = myText.Text;
}
}
The name of my ContentPlaceHolder is ContentPlaceHolderBody. I can probably find a way to do this using jQuery but I would prefer to keep this in the Codebehind. Any help is appreciated!
Not sure, but maybe this is what your looking for :
LinkButton button = sender as LinkButton;
// Get index of LinkButton that was clicked
int repeaterItemIndex = ((RepeaterItem)button.NamingContainer).ItemIndex;
foreach (RepeaterItem myRepeater in rptrWebsites.Items)
{
if (repeaterItemIndex == myRepeater.ItemIndex)
{
TextBox myText = myRepeater.FindControl("Web") as TextBox;
webName = myText.Text;
}
}
Anyway, I suggest you post more code and explain what you want to achieve. As your code seems fit for the ItemCommand pattern.
Edit : if the Button and the TextBox share the same naming container, this should also work :
LinkButton button = sender as LinkButton;
TextBox myText = button.NamingContainer.FindControl("Web") as TextBox;
webName = myText.Text;
This really seems like ItemCommand

How and WHEN to save the values of the "Checked" attribute for Dynamic checkboxes

I am adding some checkboxes dynamically during runtime, and I need to know whether they are checked or not when I reload them next time.
I load the checkbox values from a list stored in ViewState.
The question is: when do I save or check for the value of the the Checked?
I tried the event dispose for the check box and the place holder I am adding the checkboxes in, but it wasn't fired. i.e. when I put a break point it didn't stop. So any suggestions?
This is a sample code, but I don't think it is necessary:
void LoadKeywords()
{
bool add = true;
foreach (string s in (ViewState["keywords"] as List<string>))
if (s == ddlKeywords.SelectedItem.Text)
{
add = false;
continue;
}
if (add)
(ViewState["keywords"] as List<string>).Add(ddlKeywords.SelectedItem.Text);
foreach (string s in (ViewState["keywords"] as List<string>))
{
CheckBox kw = new CheckBox();
kw.Disposed += new EventHandler(kw_Disposed);
kw.Text = s;
PlaceHolderKeywords.Controls.Add(kw);
}
}
If you are dynamically adding controls at run time you have to make sure that those controls are populated to the page's Control collection before ViewState is loaded. This is so that the state of each checkbox can be rehydrated from Viewstate. The Page Load event, for example, is too late.
Typically you would dynamically add your CheckBox controls during the Init Event (before view state is loaded) and then Read the values in your Checkbox controls during the Load event (after view state is loaded).
eg:
protected override void OnInit(EventArgs e)
{
//load the controls before ViewState is loaded
base.OnInit(e);
for (int i = 0; i < 3; i++)
{
CheckBox cb = new CheckBox();
cb = new CheckBox();
cb.ID = "KeyWord" + i.ToString();
cb.Text = "Key Word"
MyPlaceHolder.Controls.Add(new CheckBox());
}
}
//this could also be a button click event perhaps?
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (Page.IsPostBack)
{
//read the checkbox values
foreach(CheckBox control in MyPlaceHolder.Controls)
{
bool isChecked = control.Checked;
string keyword = control.Text;
//do something with these two values
}
}
}
Hope that helps
****EDIT****
Forgot to mention that this is obviously just demo code - you would need to flesh it out.
For more information on dynaic control rendering in ASP.Net check out this article on 4Guys.
For more information on the page life-cycle in ASP.Net check out MSDN.
How to:
try adding a javascript code, that handles checked(),
u can get the checkboxes by using document.findElementById(ID) , then store the checkboxe's value into a hiddenfield that has a runat="server" property.
When to:
either on pageload , check if page is postback(), and check the hiddenfield(s) value(S). or add a submit button (and place its event in the code behind, runat="server" property).
hope this helps u.

Categories

Resources