2

I have a UserControl AutomatedFeedGridView.ascx which is essentially a GridView. It has a public property Category which is passed in on the page using the control.

The problem I have is that I want to filter based on a dropdown list on the calling page.

Below is the codebehind for the AutomatedFeedGridView control:

// The feed category
public Feeds.FeedCategory Category { get; set; }


protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        List<AutomatedFeed> x = Feeds.GetAutomatedFeed(Category);
        gvAutomatedFeed.DataSource = x;
        gvAutomatedFeed.DataBind();
    }

    else
    {
        List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource;

        foreach (AutomatedFeed y in x)
        {
            // if condition is not met, hide y
        }
    }

So on the first load, the GridView is bound to a List of AutomatedFeed objects. On any subsequent calls (caused by a postback on the page containing the control) I want to run some code to filter out some of the items in the GridView. The problem is this line:

List<AutomatedFeed> x = (List<AutomatedFeed>)gvAutomatedFeedCategory.DataSource;

I've tried all of the solutions here but none of them seem to work, I always get an Object reference not set to an instance error. Am I missing something or am I doing this in completely the wrong way?

I know I could easily just make another call to Feeds.GetAutomatedFeed(Category) but there must be a better way to do it than to make another stored procedure call?

Community
  • 1
  • 1
Arj
  • 1,981
  • 4
  • 25
  • 45

2 Answers2

1

you can store data source in session as Session["x"] = x ;

when page post back retrieve it back as List<AutomatedFeed> x = List<AutomatedFeed>)Session["x"];

UPDATE:

DataSource property will be null unless you explicitly re-assign and re-bind it on every postback.

You could use Session, Cache, or ViewState to keep the DataSource. But it will take more memory.

Damith
  • 62,401
  • 13
  • 102
  • 153
  • 1
    probably better to save it in the `ViewState` – Magnus Oct 02 '11 at 18:15
  • Thanks, this is enough to solve my problem without having to re-execute the stored procedure. I hadn't used `ViewState` programatically before. [This video](http://www.asp.net/general/videos/how-do-i-save-and-load-view-state-information-for-a-custom-web-server-control) is simple but explains the basics in case anyone else is interested. – Arj Oct 02 '11 at 22:31
0

The control is only generated and populated after the page.load, so it will not contain any data.

Christian
  • 3,708
  • 3
  • 39
  • 60