Data used by several usercontrols - asp.net

I have a page with several different usercontrols.
All of them run the following code:
var member = System.Web.Security.Membership.GetUser();
MemberProfile mp = MemberProfile.GetUserProfile(member.UserName);
string affilID = mp.GetPropertyValue("aID").ToString();
I would like to get this value once and save it for use with all the controls.
I'm not sure where in the life cycle I need to do this to insure it is accessible to all the controls when they are being rendered.
Any suggestions?
Thank you!

Why not do it in the Page_Load event with Session? Maybe something like this (C#):
MembershipUser member;
MemberProfile mp;
string affilID;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["member"] != null)
{
member = (MembershipUser)Session["member"];
}
else
{
member = System.Web.Security.Membership.GetUser();
}
if (Session["mp"] != null)
{
mp = (MemberProfile)Session["mp"];
}
else
{
mp = MemberProfile.GetUserProfile(member.UserName);
}
if (Session["affilID"] != null)
{
affilID = (string)Session["affilID"];
}
else
{
affilID = mp.GetPropertyValue("aID").ToString();
}
}

If it's all on the same page, as long as it's outside of a subroutine you should be able to use it within any subroutine. Or am I missing something?

Related

ASP.net Page pageload called in postback with IsPost back = false

Hi everyone i have a strange problem which I hope u can help me with,
i have a normal Asp.net page in which i handle some state data in the page load like this
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["TempD"] = null;
Session["Totals"] = null;
//Handling Sessions here...
}
}
the problem is at a button post back the page_load gets called twice once with IsPostBack
= true which is ok , the second time however IsPostBack = false!!! which cause my code to enter the if condition and reset the state information which is not ok, i use some Ajax Toolkit controls in the page no update panels just some calenders and AutoCompletes.
here is the code for the button causing the post back
protected void TSBtnAddItem_Click(object sender, EventArgs e)
{
if (Session["TempD"] != null)
{
DataLayer.Invoicing.CInvoiceDetail InvoDetails = (DataLayer.Invoicing.CInvoiceDetail)Session["TempD"];
DataLayer.Invoicing.CVarInvoiceDetail var = new DataLayer.Invoicing.CVarInvoiceDetail();
if (LblCurrencyValue.Visible)
{
var.CurencyID = int.Parse(LblCurrencyValue.ToolTip);
}
else
{
var.CurencyID = int.Parse(CboCurrencyValue.SelectedValue);
}
var.ID = 0;
var.InvoiceHeaderID = Convert.ToInt64(InvoiceHeaderID.Value);
var.IsChanges = true;
var.IsFreightItem = false;
var.IsOption = true;
var.ItemAmount = decimal.Parse(txtItemVal.Text);
var.ItemName = CboItemName.SelectedItem.Text;
var.ItemID = int.Parse(CboItemName.SelectedValue);
var.Remarks = "";
if (IsPartLoad.Checked == true)
{
ShipLink.Publics.ApplicationMethods.Item32 itm = LstCalcType.Find(delegate(ShipLink.Publics.ApplicationMethods.Item32 p1) { return Convert.ToInt32(p1.Name.Trim()) == var.ItemID; });
if (itm == null)
{
ADDToCalcList(Convert.ToString(var.ItemID));
if (NumUpDownPortRatio.Enabled == false)
var.ItemAmount = ChangeAmount(var.ItemID, var.ItemAmount);
}
}
InvoDetails.lstCVarInvoiceDetail.Add(var);
Session["TempD"] = InvoDetails;
UGrdInvoiceDetailGrid.DataSource = InvoDetails.lstCVarInvoiceDetail;
UGrdInvoiceDetailGrid.DataBind();
CalcSalesTax();
CalcDiscount();
AddCaseUGrdInvoiceTotalGrid();
}
}
Have a look at this: What is the difference between Page.IsPostBack and Page.IsCallBack?
Integrate if (!IsCallBack) and you should be fine.
I found a solution for this. If you have an global.asax in the project, you need add a new route with "" in a url alias. An example:
private void Generteroutes(RouteCollection routes) {
routes.MapPageRoute("home", "", "~/Default.aspx");
}
load this in Application_Start and problem solved.

Posting data between Asp.Net Web Pages

I have a list of strings, which are generated on a imagebutton_click method. I want to be able to use this list in another webpage.
How ever im not quite sure how to go about posting it between the two pages.
I have the following code below:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
RadGrid rg = RadGrid1;
//Get selected rows
GridItemCollection gdc = (GridItemCollection)rg.SelectedItems;
foreach (GridItem gi in gdc)
{
if (gi is GridDataItem)
{
GridDataItem gdi = (GridDataItem)gi;
if (!string.IsNullOrEmpty(gdi["Email"].Text))
{
string client = gdi["Email"].Text;
//Creating a List of Clients to be Emailed
emailList.Add(email);
}
}
//Enable the Prepare Email Page
PageView2.Selected = true;
}
protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
{
if (emailList.Count != 0)
{
for (int i = 0; i < emailList.Count; i++)
{
_to = emailList[i].ToString() + ";";
}
}
else
{
_to = emailList[1].ToString();
}
//Processing Client Email
string _from = sec.GetCurrentUserEmail("test");
string _cc = "";
string _subject = SubjectTB.Text;
string _body = EmailEditor.Content;
string _tempTo = sec.GetCurrentUserEmail("temp");
string _msg = sec.SendMail(_tempTo, _cc, _from, _subject, _body, "");
if (_msg == "success")
{
//Thank the user and record mail was delivered sucessfully
TestPanel.Visible = true;
}
}
How do I get the values of emailList to be passed through to ImageButton2_click(object sender, ImageClickEventArgs e). Currently it just passes through a null value. I gather I need to use HTML forms to do the request. Thanks.
I'm guessing that emailList is a private variable? Wouldn't you be able to add that to the LoadControlState and SaveControlState so that it'll be available for ImageButton2_Click later?
Here is an example: http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadcontrolstate%28v=vs.80%29.aspx
Another possibility is hidden field, that might be the simplist way, but not as secure.
You can get a good idea about state management in ASP.Net here. For your case if button1 and button2 are in the same aspx page, Viewstate would be a good idea. If they are in diferent pages then use Session state management.

Find all textbox control in a page

i am trying to use http Module to disable textbox of each page. Here is my sample coding
public void context_OnPreRequestHandlerExecute(object sender, EventArgs args)
{
try
{
HttpApplication app = sender as HttpApplication;
if (app != null)
{
Page page = app.Context.Handler as Page;
if (page != null)
{
page.PreRender += OnPreRender;
page.PreLoad += onPreLoad;
}
}
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
public void OnPreRender(object sender, EventArgs args)
{
Page page = sender as Page;
if (page.IsCrossPagePostBack)
{
DisableAllTextBoxes(page);
}
}
private static void DisableAllTextBoxes(Control parent)
{
foreach (Control c in parent.Controls)
{
var tb = c as Button;
if (tb != null)
{
tb.Enabled = false;
}
DisableAllTextBoxes(c);
}
}
This coding can work very well but when i use server.transer to another page. Button are not able to disable already.
For example webform1 transfer to webform2. Webform 1's button is able to disable but webform2 is not able to disable. Can anyone solve my problem?
Server.Transfer DOES NOT go through all http module pipline (thats why context_OnPreRequestHandlerExecute isn't executed for you )
you should try Server.TransferRequest or response.redirect or HttpContext.Current.RewritePath
Use LINQ to get all your textbox controls.
Don't use Server.Transfer()
Create an extension method on ControlCollection that returns an IEnumerable. That handles the recursion. Then you could use it on your page like this:
var textboxes = this.Controls.FindAll().OfType<TextBox>();
foreach (var t in textboxes)
{
t.Enabled = false;
}
...
public static class Extensions
{
public static IEnumerable<Control> FindAll(this ControlCollection collection)
{
foreach (Control item in collection)
{
yield return item;
if (item.HasControls())
{
foreach (var subItem in item.Controls.FindAll())
{
yield return subItem;
}
}
}
}
}
Taken from this answer.

Textbox value null when trying to access it

namespace Dynamic_Controls.Dropdowndynamic
{
public partial class DropdowndynamicUserControl : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (ControlCount != 0)
{
Recreatecontrols();
}
}
private void Recreatecontrols()
{
// createtextboxes(ControlCount);
createtextboxes(2);
}
protected void createtextboxes(int ControlCount)
{
DynPanel.Visible = true;
for (int i = 0; i <= ControlCount; i++)
{
TextBox tb = new TextBox();
tb.Width = 150;
tb.Height = 18;
tb.TextMode = TextBoxMode.SingleLine;
tb.ID = "TextBoxID" + this.DynPanel.Controls.Count;
tb.Text = "EnterTitle" + this.DynPanel.Controls.Count;
tb.Load+=new EventHandler(tb_Load);
tb.Visible = true;
tb.EnableViewState = true;
DynPanel.Controls.Add(tb);
DynPanel.Controls.Add(new LiteralControl("<br/>"));
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
Int32 newControlCount = Int32.Parse(DropDownList1.SelectedValue);
//createtextboxes(newControlCount);
//ControlCount+=newControlCount;
createtextboxes(2);
}
protected void Button1_Click(object sender, EventArgs e)
{
readtextboxes();
}
public void readtextboxes()
{
string x = string.Empty;
for (int a = 0; a < DynPanel.Controls.Count; a++)
{
foreach (Control ctrl in DynPanel.Controls)
{
if (ctrl is TextBox)
{
x = ((TextBox)ctrl).Text;
}
x+=x+("\n");
}
Result.Text = x;
}
}
private Int32 ControlCount
{
get
{
if (ViewState["ControlCount"] == null)
{
ViewState["ControlCount"] = 0;
}
return (Int32)ViewState["ControlCount"];
}
set
{
// ViewState["ControlCount"] = value;
ViewState["ControlCount"] = 2;
}
}
private void tb_Load(object sender, EventArgs e)
{
LblInfo.Text = ((TextBox)sender).ID + "entered";
}
}
}
Are you adding these controls dynamically in Page_Load (by, I'm assuming, calling your AddRequiredControl() method)? If so, is it wrapped in a conditional which checks for IsPostBack? The likely culprit is that you're destructively re-populating the page with controls before you get to the button click handler, so all the controls would be present but empty (as in an initial load of the page).
Also, just a note, if you're storing each control in _txt in your loop, why not refer to that variable instead of re-casting on each line. The code in your loop seems to be doing a lot of work for little return.
You need to recreate any dynamically created controls on or before Page_Load or they won't contain postback data.
I'm not entirely clear what happens on DropdownList changed - are you trying to preserve anything that has been entered already based on the textboxes previously generated?
In any event (no pun intended) you need to recreate exactly the same textboxes in or before Page_Load that were there present on the postback, or there won't be data.
A typical way to do this is save something in ViewState that your code can use to figure out what to recreate - e.g. the previous value of the DropDownList. Override LoadViewState and call the creation code there in order to capture the needed value, create the textboxes, then in the DropDownList change event, remove any controls that may have been created in LoadViewState (after of course dealing with their data) and recreate them based on the new value.
edit - i can't figure out how your code works now, you have AddRequiredControl with parameters but you call it with none. Let's assume you have a function AddRequiredControls that creates all textboxes for a given DropDownList1 value, and has this signature:
void AddRequiredControls(int index)
Let's also assume you have a PlaceHolder called ControlsPlaceholder that will contain the textboxes. Here's some pseudocode:
override void LoadViewState(..) {
base.LoadViewState(..);
if (ViewState["oldDropDownIndex"]!=null) {
AddRequiredControls((int)ViewState["oldDropDownIndex"]);
}
}
override OnLoad(EventArgs e)
{
// process data from textboxes
}
void DropDownList1_SelectedIndexChanged(..) {
ControlsPlaceholder.Controls.Clear();
AddRequiredControls(DropDownList1.SelectedIndex);
ViewState["oldDropDownIndex"]=DropDownList1.SelectedIndex;
}

DetailsView Item events (updated deleted) with same handler

I'm using a details view in my asp.net web application.
When it fires its updated and inserted events I'd like to handle them the same way. Because the event args they have are two separate classes with no common inheritance I have to have two separate methods with basically the same code.
Is there any way around this?
eg.
protected void DetailsViewItemInserted(object sender, DetailsViewInsertedEventArgs e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInInsertMode = e.ExceptionHandled;
}
}
protected void DetailsViewItemUpdated(object sender, DetailsViewUpdatedEventArgs e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
}
I'd like to extract
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
into some kind of common method if possible.
I agree it is disappointing that these classes inherit directly from EventArgs. It seems logical that they would inherit from the same sublass of EventArgs given not just their common properties, but the fact that most times you use a DetailsView for inserting you also use it for updating.
That being said, what you want to do can be accomplished with a bit of dynamic C#. It's pretty cool, and maybe even a little elegant, albeit a little more overhead.
Try this: (requires C# 4.0)
protected void DetailsView1_Inserted(Object sender, DetailsViewInsertedEventArgs e)
{
ProcessDetailsViewEventArgs(e);
}
protected void DetailsView1_Updated(Object sender, DetailsViewUpdatedEventArgs e)
{
ProcessDetailsViewEventArgs(e);
}
private void ProcessDetailsViewEventArgs(dynamic e)
{
if (e == null)
return;
if (e.Exception != null)
{
e.ExceptionHandled = HandleException(e.Exception);
e.KeepInEditMode = e.ExceptionHandled;
}
}
Use the OnItemCommand, & give your Edit & Delete buttons CommandNames. This event will handle both scenarios for you.

Resources