Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

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?

share|improve this question
add comment

3 Answers

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.

share|improve this answer
    
A helper class seems to be the best solution. –  HutzelGutzel Dec 15 '11 at 8:34
    
The easiest way to share the code would be a common base class for both web parts. –  Bernd Rickenberg Jan 11 '12 at 7:21
add comment

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

share|improve this answer
    
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 –  HutzelGutzel Dec 14 '11 at 14:45
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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