Unable to retain value of a label during post back(button click) in sharepoint - sharepoint

While writing code for connecting two webparts,I created a two labels. the text value for both the labels were written in OnPreRender method. However, i forgot to add control for one label in CreateChildControl method.
So while debugging, i noticed that, after post back, the label whose control i forgot to add didn't retain the value and it was showing empty string.But the other label who's control i added was able to retain the value.
protected override void CreateChildControls()
{
base.CreateChildControls();
btnup.Text = " Update";
this.Controls.Add(lblid);//**If i add this, the label retains the value during post back , otherwise its null**
this.Controls.Add(lblname);
this.Controls.Add(lbldesig);
this.Controls.Add(tbdes);
this.Controls.Add(lblcomp);
this.Controls.Add(tbcomp);
this.Controls.Add(btnup);
btnup.Click += new EventHandler(btnup_Click);
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (connectionInterface != null)
{
id = connectionInterface.parameter1;
SPWeb mysite = SPContext.Current.Web;
SPList mylist = mysite.Lists["UpdateList"];
SPListItemCollection itemcol = mylist.Items;
foreach (SPListItem itm in itemcol)
{
string nm = itm["Company_Id"].ToString();
if (nm.Equals(id))
{
lblid.Text = itm["Company_Id"].ToString();
lblname.Text = itm["Name"].ToString();
l
}
}
}
else
{
lblname.Text = "nothing is recieved!";
}
}
Why is it behaving like this?

This is a normal behavior. If you don't add the control to Controls collection, ASP.NET framework will not preserve its value in postback and hence will be lost during postback.

Related

Acumatica - Need Help in Updating Activities in Project Quotes Screen PM304500 through custom action

I have a custom action on screen CR304000 - OpportunityMaint in the Quotes tab of the grid view that marks a field called IsPrimary in the CRQuote DAC as true for the current record in the Quotes view. These project Quotes are associated with the current opportunity as well as with a related PMQoute in the PMQuoteMaint BLC. The PMQuoteMaint BLC has a view called Activties that has all the CRActivities associated with the PMQuote. I created a custom field in the CRActivity called IsPrimary and added it to the Activities view in the PMQuoteMaint BLC grid.
My goal was to override the Action in the OpportunityMaint to update the IsPrimary field in CRActivity to true or false depending on what the Action in OpportunityMaint is toggling. However, my IsPrimary field in PMQuoteMaint is not toggling. My code attempts to get Current Quote OpportunityMain and then create a PMQuoteMaint graph and set the Current record. Then iterate though Activies view and set the IsPrimary field accordingly. Like I said, not having success because I'm not sure that my code is successfully retrieving the correct Activities.
There might be a better way to access CRActivity associated with a PMQuote, but I'm not sure. Any help would be appreciated. Here is code:
public virtual IEnumerable PrimaryQuote(PXAdapter adapter)
{
foreach (CROpportunity opp in adapter.Get())
{
if (Quotes.Current?.IsPrimary != true)
{
var selectExistingPrimary = new PXSelect<CRQuote, Where<CRQuote.quoteID,
Equal<Required<CRQuote.quoteID>>>>(this);
CRQuote primary = selectExistingPrimary.Select(opp.DefQuoteID);
if (primary != null && primary.QuoteID != Quotes.Current.QuoteID && primary.Status ==
PM.PMQuoteStatusAttribute.Closed)
{
throw new PXException(PM.Messages.QuoteIsClosed, opp.OpportunityID,
primary.QuoteNbr);
}
var quoteID = Quotes.Current.QuoteID;
var opportunityID = this.Opportunity.Current.OpportunityID;
this.Persist();
PXDatabase.Update<Standalone.CROpportunity>(
new PXDataFieldAssign<Standalone.CROpportunity.defQuoteID>(quoteID),
new PXDataFieldRestrict<Standalone.CROpportunity.opportunityID>(PXDbType.VarChar,
255, opportunityID, PXComp.EQ)
);
this.Cancel.Press();
CROpportunity rec = this.Opportunity.Search<CROpportunity.opportunityID>
(opportunityID);
yield return rec;
}
yield return opp;
}
``` My OverRide
public PXAction<CROpportunity> primaryQuote;
[PXUIField(DisplayName = Messages.MarkAsPrimary)]
[PXButton]
public virtual IEnumerable PrimaryQuote(PXAdapter adapter)
{
// this is currently selected record in quotes grid
var currQuoteNbr = Base.Quotes.Current.QuoteNbr;
bool isPrimary2;
foreach (CRQuote quote in Base.Quotes.Select())
{
var quoteNbr = quote.QuoteNbr;
if(quoteNbr.Trim() == currQuoteNbr.Trim())
{
isPrimary2 = true;
}
else
{
isPrimary2 = false;
}
PXTrace.WriteInformation(string.Format("Quote: {0} Value:
{1}",quoteNbr.ToString(),isPrimary2.ToString()));
var PMQuoteMaintGraph = PXGraph.CreateInstance<PMQuoteMaint>();
PMQuoteMaintGraph.Quote.Current = PMQuoteMaintGraph.Quote.Search<PMQuote.quoteNbr>
(quoteNbr.Trim()); // this is the current quote
foreach (CRActivity activity in PMQuoteMaintGraph.Activities.Select())
{
CRActivityExt itemExt = PXCache<CRActivity>.GetExtension<CRActivityExt>(activity);
itemExt.UsrPrimary = isPrimary2;
PMQuoteMaintGraph.Activities.Cache.Persist(PXDBOperation.Update);
PXDatabase.Update<CRActivity>(new PXDataFieldAssign<CRActivityExt.usrPrimary>
(isPrimary2));
}
}
return Base.primaryQuote.Press(adapter);
}

Custom Filter Web Part to filter/update ListView Web Part

Scenario : I need Refresh/Filter the Items/records displayed in List View Web Part on the same page based on selected filters. So I created Visual Web Part and tried to modify the View of List View Web Part Programmatically. So far i have reached till here :
string spListName = "Job";
protected void BtnSearchClick(object sender, EventArgs e)
{
try
{
SPWeb oWebsite = SPContext.Current.Web;
SPList oList = oWebsite.Lists[spListName];
XsltListViewWebPart xsltWP = null;
SPWebPartManager wpManager = WebPartManager.GetCurrentWebPartManager(Page) as SPWebPartManager;
//Code to Find List View Web Part on Page
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpManager.WebParts)
{
if (wp.GetType().Name == "XsltListViewWebPart")
xsltWP = wp as XsltListViewWebPart;
}
oWebsite.AllowUnsafeUpdates = true;
StringBuilder strbPreQuery = new StringBuilder("<Where><Eq>");
StringBuilder strbPostQuery = new StringBuilder("</Value></Eq></Where>");
string strQueryKeyword = "<FieldRef Name='Customer' /><Value Type='Lookup'>";
SPQuery oQuery = new SPQuery();
oQuery.Query = strbPreQuery.ToString() + strQueryKeyword + txtCustomer.Text + strbPostQuery.ToString();
SPListItemCollection itemCol = oWebsite.Lists[spListName].GetItems(oQuery);
PropertyInfo pi = xsltWP.GetType().GetProperty("ContextView", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
SPView view = (SPView)(pi.GetValue(xsltWP, null));
view.Query = oQuery.Query;
view.Update();
wpManager.SaveChanges(xsltWP);
xsltWP.DataBind();
oWebsite.AllowUnsafeUpdates = false;
}
catch (Exception ex)
{
Response.Write(ex);
}
}
The Above code works but now I am facing following problems :
The results updation requires page refresh so If I add following code, results are updated but filter values in visual web part is lost.
this.Context.Response.Redirect(this.Context.Request.Url.ToString());
Filtered applied by one user is also reflected to another user.
Can some please help in to address these two problems I have ? that is I want
To preserve the filter values and results to be modified at the same time
The filtering should be only for one user and not for all.
Any help in this regards will be appreciated.
Create a SPQuery that will hold the default value of the view.
then after passing the value,
Use this to revert back the default query of the view.
SPView _view;
protected void Page_Unload(object sender, EventArgs e)
{
//your code
SPView view = (SPView)(pi.GetValue(xsltWP, null));
view.Query = _view.Query;
view.Update();
}

Save values between page navigation in Windows Phone

How do I save values between page navigation in windows phone,
suppose I have two text blocks in my one phone application page, and they contains dynamically changing values every time, now suppose my text block have value "abc" and for some reason I go back to previous page, now when I get back on my page, I want that text block having value "abc". How to do it??
There are several methods available
IsolatedStorageSettings
Save
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
// txtInput is a TextBox defined in XAML.
if (!settings.Contains("userData"))
{
settings.Add("userData", txtInput.Text);
}
else
{
settings["userData"] = txtInput.Text;
}
settings.Save();
Read
if (IsolatedStorageSettings.ApplicationSettings.Contains("userData"))
{
txtDisplay.Text +=
IsolatedStorageSettings.ApplicationSettings["userData"] as string;
}
PhoneApplicationService.Current.State
PhoneApplicationService.Current.State["param"] = param
and on other page we can get it like this.
var k = PhoneApplicationService.Current.State["param"];
Define two static variable in your App.xaml.cs
public static valueOne = string.Empty;
public static valueTwo = string.empty;
//Assign textbox value to variable on page leaving event
protected override void OnNavigatingFrom(System.Windows.Navigation.NavigatingCancelEventArgs e)
{
if(!string.IsNullOrEmpty(txtBoxOne.Text))
App.valueOne = txtBoxOne.Text;
if(!string.IsNullOrEmpty(txtBoxTwo.Text))
App.valueTwo = txtBoxTwo.text;
}
//Get value from page load
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if(!string.IsNullOrEmpty(App.valueOne))
string valueFirst = App.valueOne;
if(!string.IsNullOrEmpty(App.valueTwo ))
string valueTwo = App.valueTwo ;
}
There are various approaches to solve this.
Common thing is using a Static Class, which holds static properties and binding it to your View.

How can I remove the tables rendered around the webparts in the Rich Content area?

How would I override the tables rendered around the webparts in the "Rich Content" area?
I have successfully removed the tables around webpartzones and their webparts but can't figure how to remove the tables around Rich Content area webparts.
I am not using the Content Editor WebPart.
The "Rich Content" area I am using is created using the PublishingWebControls:RichHtmlField.
This is the control which has content and webparts.
Bounty here.
I have pondered this myself in the past and I've come up with two options, though none are very appealing, so have not implemented them:
Create a custom rich text field. Override render, call base.Render using a TextWriter object and place the resulting html in a variable, which you then "manually" clean up, before writing to output.
Create a custom rich text field. Override render, but instead of calling base.Render, take care of the magic of inserting the webparts yourself. (This is probably trickier.)
Good luck!
Update, some example code I use to minimize the output of the RichHtmlField:
public class SlimRichHtmlField : RichHtmlField
{
protected override void Render(HtmlTextWriter output)
{
if (IsEdit() == false)
{
//This will remove the label which precedes the bodytext which identifies what
//element this is. This is also identified using the aria-labelledby attribute
//used by for example screen readers. In our application, this is not needed.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);
base.Render(htw);
htw.Flush();
string replaceHtml = GetReplaceHtml();
string replaceHtmlAttr = GetReplaceHtmlAttr();
sb.Replace(replaceHtml, string.Empty).Replace(replaceHtmlAttr, string.Empty);
output.Write(sb.ToString());
}
else
{
base.Render(output);
}
}
private string GetReplaceHtmlAttr()
{
return " aria-labelledby=\"" + this.ClientID + "_label\"";
}
private string GetReplaceHtml()
{
var sb = new StringBuilder();
sb.Append("<div id=\"" + this.ClientID + "_label\" style='display:none'>");
if (this.Field != null)
{
sb.Append(SPHttpUtility.HtmlEncode(this.Field.Title));
}
else
{
sb.Append(SPHttpUtility.HtmlEncode(SPResource.GetString("RTELabel", new object[0])));
}
sb.Append("</div>");
return sb.ToString();
}
private bool IsEdit()
{
return SPContext.Current.FormContext.FormMode == SPControlMode.Edit || SPContext.Current.FormContext.FormMode == SPControlMode.New;
}
}
This code is then used by your pagelayout like this:
<YourPrefix:SlimRichHtmlField ID="RichHtmlField1" HasInitialFocus="false" MinimumEditHeight="200px" FieldName="PublishingPageContent" runat="server" />
Got it:
https://sharepoint.stackexchange.com/a/32957/7442

Updating the url of a navigation node in moss programatically

Can anyone see why this should not work:
SPSite topNavigationSite = new SPSite("http://moss");
SPWeb topNavigationWeb = topNavigationSite.OpenWeb();
SPNavigationNodeCollection topNavigationBarNodes = topNavigationWeb.Navigation.TopNavigationBar;
SPNavigationNode updateNode = topNavigationBarNodes.Navigation.GetNodeByUrl("/about");
updateNode.Url = "";
topNavigationWeb.Update();
I can see debugging that the url get's set to "" but when the page renders, the navigation still shows the url as /about/default.aspx
I'm running this in page_load and expected it to update the moss database with the new url value.
I know this is 3years old! but as there is no where online about updating a current url!
I had to do some debugging and this is what iv come up with! By the way I got the hint from
topNavigationWeb.Update();
indicating that its updating a list! hint hint!
a bit of background! I wanted to update the quick links from a list when they add, update and delete an item from the list! On my list I have two columns Title and URL!
I then created a project in VS 2010, its an event receiver that is connected only to that list (done in the elements.xml file)
within the .cs file I added item added, item deleting(not deleted ;) ) and item updated
public override void ItemAdded(SPItemEventProperties properties)
public override void ItemUpdated(SPItemEventProperties properties)
public override void ItemDeleting(SPItemEventProperties properties)
now within each method you can simply call this method!
add/update
public static void AddQuickLaunchItem(string header, string url, SPWeb web)
{
SPNavigationNodeCollection quickLaunch = web.Navigation.QuickLaunch;
// try to get quick launch header
SPNavigationNode nodeHeader =
quickLaunch.Cast<SPNavigationNode>().Where(n => n.Title == header).FirstOrDefault();
//if header not found create it
if (nodeHeader == null)
{
nodeHeader = quickLaunch.AddAsFirst(new SPNavigationNode(header, url,true));
}
else
{
web.AllowUnsafeUpdates = true;
nodeHeader = quickLaunch.Cast<SPNavigationNode>().Where(n => n.Title == header).First() ;
nodeHeader.Url = url;
web.AllowUnsafeUpdates = false;
}
nodeHeader.Update();
web.Update();
}
the first part is checking if the node exists using the title (header)! I'm comparing between what headers there are and from the list item:
SPNavigationNode nodeHeader =
quickLaunch.Cast<SPNavigationNode>().Where(n => n.Title == header).FirstOrDefault();
this part is the comparison:
n.Title == header
I'm getting these values (header and url / spweb) like so:
public static void AddQuickLaunchItem(string header, string url, SPWeb web)
the method that is calling the above would look like this:
private void addloopweblinks(SPSite siteCollection, SPItemEventProperties properties)
{
// Enumerate through each site and apply branding.
foreach (SPWeb web in siteCollection.AllWebs)
{
AddQuickLaunchItem(properties.ListItem["Title"].ToString(), properties.ListItem["URL"].ToString(), web);
}
}
and the above method is called within the itemadded and itemupdated ;) passing the values like so:
public override void ItemAdded(SPItemEventProperties properties)
{
using (SPSite siteCollection = new SPSite(properties.WebUrl))
{
if (siteCollection != null)
{
addloopweblinks(siteCollection, properties);
}
}
}
similar things can be done for the delete ;)
SPNavigationNode nodeHeader =
quickLaunch.Cast().Where(n => n.Title == header).FirstOrDefault();
that will get the node!
nodeHeader.delete();
nodeHeader.update();
that will delete the item!
so in your case what you need, I don't know if you noticed it was this part:
web.AllowUnsafeUpdates = true;
nodeHeader = quickLaunch.Cast<SPNavigationNode>().Where(n => n.Title == header).First() ;
nodeHeader.Url = url;
web.AllowUnsafeUpdates = false;
nodeHeader.Update();
web.Update();
as you can see what i mean by the hint! nodeHeader.Update(); didnt update the url, when debugging it does change but when i go to the update part it doesnt work :( and it clicked in i need web.AllowUnsafeUpdates = true; loool only becuse I experienced a similar situation before!
for you it would be:
using(SPSite topNavigationSite = new SPSite("http://moss"))
{
using(SPWeb topNavigationWeb = topNavigationSite.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPNavigationNodeCollection topNavigationBarNodes =topNavigationWeb.Navigation.TopNavigationBar;
SPNavigationNode updateNode = topNavigationBarNodes.Navigation.GetNodeByUrl("/about");
updateNode.Url = "";
updateNode.Update();
web.Update();
web.AllowUnsafeUpdates = false;
}
}
If the user doesnt have the sufficent rights than you need to encapsulate the above with runwithelevatedprivalages :) hope this helps :)
Have you tried:
updateNode.Update();
topNavigationWeb.Update();
It doesn't look like you are updating the SPNavigationNode object. (Note: you may not need the second Update call.)

Resources