1

I have a class "Wepart A" and a class "Webpart B" which have some similiarities. So I introduced a BaseWebpart from which A and B inherit.

I want to share 2 properties (SortColumn and SortDirection) which are stored in viewstate:

protected string SortRow
{
  get
  {
    object o = ViewState["SortRow"];
    if (o == null)
    {
      return String.Empty;
    }
    return (string)o;
  }
  set
  {
    if (value == SortRow)
    {
      SortAscending = !SortAscending;
    }
    ViewState["SortRow"] = value;
  }
}

protected bool SortAscending
{
  get
  {
    object o = ViewState["SortAscending"];
    if (o == null)
    {
      return true;
    }
    return (bool)o;
  }
  set
  {
    ViewState["SortAscending"] = value;
  }
}

and put them to the BaseWebpart. Can I access them in Webpart A and B without problems? I guess the ViewState-Keys could be a problem...any suggestions?

3 Answers 3

1

I think you answered your own question in your comment:

So I better go for using getter and setter methods with different keys for the viewstate.

You can have a unique key with 'this.ID', which give you the webpart 'guid'. If you want to share similar logic between webparts or controls in general, you can also create a static 'helper' class.

2
  • A helper class seems to be the best solution.
    – Tom Bola
    Commented Dec 15, 2011 at 8:34
  • The easiest way to share the code would be a common base class for both web parts. Commented Jan 11, 2012 at 7:21
0

Its better to use web part connections for this purpose. You can make one web part as Connection Provider and other as Connection Consumer and define a static connection between them.

Answer shared from this post -

http://social.msdn.microsoft.com/Forums/en/sharepointdevelopment/thread/d9bdafab-5cb1-4b2e-ae04-a63446f8404e

1
  • I don't want to share the values in the viewstate between the webparts, I only want to use the same functionality to get and set the SortColumn and SortOrder in ViewState. So I better go for using getter and setter methods with different keys for the viewstate
    – Tom Bola
    Commented Dec 14, 2011 at 14:45
0

Because the ViewState property is marked as protected, you can't get a control's(or webpart) ViewState in another.

If you want to share data between page controls\webparts per-request basis(similar to viewstate), use HttpContext.Items instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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