【问题标题】:Getting items in GridView after it's been bound绑定后在 GridView 中获取项目
【发布时间】:2011-10-02 15:36:56
【问题描述】:

我有一个 UserControl AutomatedFeedGridView.ascx,它本质上是一个 GridView。它有一个公共属性Category,使用控件在页面上传递。

我的问题是我想根据调用页面上的下拉列表进行过滤。

下面是AutomatedFeedGridView 控件的代码隐藏:

// 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
        }
    }

所以在第一次加载时,GridView 被绑定到AutomatedFeed 对象的列表。在任何后续调用(由包含控件的页面上的回发引起)我想运行一些代码来过滤掉 GridView 中的一些项目。问题是这一行:

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

我已经尝试了所有here 的解决方案,但它们似乎都不起作用,我总是收到 Object reference not set to an instance 错误。我是否遗漏了某些东西,或者我这样做的方式完全错误?

我知道我可以轻松地再次调用 Feeds.GetAutomatedFeed(Category),但一定有比再次调用存储过程更好的方法吗?

【问题讨论】:

    标签: c# .net gridview user-controls postback


    【解决方案1】:

    您可以将会话中的数据源存储为Session["x"] = x ;

    当页面回发时将其检索为List&lt;AutomatedFeed&gt; x = List&lt;AutomatedFeed&gt;)Session["x"];

    更新:

    DataSource 属性将为 null,除非您在每次回发时明确地重新分配和重新绑定它。

    您可以使用 Session、Cache 或 ViewState 来保留 DataSource。但它会占用更多的内存。

    【讨论】:

    • 最好保存在ViewState
    • 谢谢,这足以解决我的问题,无需重新执行存储过程。我以前没有以编程方式使用过ViewStateThis video 很简单,但解释了基础知识,以防其他人感兴趣。
    【解决方案2】:

    该控件仅在 page.load 之后生成和填充,因此它不会包含任何数据。

    【讨论】:

      猜你喜欢
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      相关资源
      最近更新 更多