0

Alright so I want my view to update when clicking a button. Which kinda works, but I have to click twice to see my changes. From what Ive read the problem might be solved using OnPreRender(), but I dont understand how :/ ...My code looks like this:

public class VisualWebPart1 : WebPart
    {
        // Visual Studio might automatically update this path when you change the Visual Web Part project item.
        private const string _ascxPath = @"~/_CONTROLTEMPLATES/cp5/VisualWebPart1/VisualWebPart1UserControl.ascx";

        Button btn;
        TextBox txtfld;
        SPWeb curweb;
        WebPart myWebPart;
        SPList list;
        SPView currentView;

        Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager manager;

        protected override void CreateChildControls()
        {
            txtfld = new TextBox();
            btn = new Button();
            btn.Text = "updateview";
            btn.Click += new EventHandler(updateAllProducts_Click);

            curweb = SPContext.Current.Web;

            manager = curweb.GetLimitedWebPartManager("/SitePages/Home.aspx", PersonalizationScope.Shared);

            foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in manager.WebParts)
            {
                if (webpart.Title == "jlist")
                {
                    myWebPart = webpart;
                }   
            }

            foreach (SPList l in curweb.Lists)
            {
                if (l.Title == "jlist")
                {
                    list = l;
                }
            }

            foreach (SPView v in list.Views)
            {
                if (v.Title == "")
                {
                    currentView = v;
                }
            }

            //this.Controls.Add(debug);
            this.Controls.Add(btn);
            this.Controls.Add(txtfld);            
        }



        void updateAllProducts_Click(object sender, EventArgs e)
        {
            string q = "<Where><Eq><FieldRef Name='Title'/><Value Type='Text'>" + txtfld.Text + "</Value></Eq></Where>";

            currentView.Query = q;
            currentView.Update();
            manager.SaveChanges(myWebPart);
        }
    }
0

try to put everything from btn.click until this.Controls.Add(btn) (both not included) into OnPreRender function. This way you just create the controls on CreateChildControls but you populate them on PreRender...it worked for me :) oh and add EnsureChildControls() into your OnPreRender function to make sure the controls are created.

  • Thanks alot for your answer. But im still struggling with this. I dont know if I missed something but the problem now, is that "currentview" is null when I try to update it with my click. – Jukke Oct 11 '13 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.