c# - 绑定(bind)后在 GridView 中获取项目

标签 c# .net gridview user-controls postback

我有一个 UserControl AutomatedFeedGridView.ascx,它本质上是一个 GridView。它有一个公共(public)属性 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 绑定(bind)到 AutomatedFeed 对象列表。在任何后续调用(由包含控件的页面上的回发引起)中,我想运行一些代码来过滤掉 GridView 中的一些项目。问题是这一行:

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

我已经尝试了所有的解决方案 here但它们似乎都不起作用,我总是收到 Object reference not set to an instance 错误。我是否遗漏了什么,或者我是否以完全错误的方式执行此操作?

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

最佳答案

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

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

更新:

DataSource 属性将为空,除非您在每次回发时显式地重新分配和重新绑定(bind)它。

您可以使用 Session、Cache 或 ViewState 来保留数据源。但是会占用更多的内存。

关于c# - 绑定(bind)后在 GridView 中获取项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7627303/

相关文章:

c# - 使用 LINQ 将列表转换为列表的列表

c# - c# 中的 openfiledialogue 正在选择多个值,但它选择最后一个选定项作为第一个

c# - 如何在 catch block 中从 Assert.Multiple 获取所有已保存的结果?

c# - DefaultValueAttribute 似乎没有效果

.net - .Net 中的程序集 DLL 管理

c# - 如何从 GridView 中删除时间戳

android - 简单静态图库的内存不足异常

c# - Entity Framework Code First Web.API 中的一对多关系

c# - 使用单击事件将图像按钮添加到 c# 中的 gridview header

c# - 整个解决方案的Visual Studio快速切换平台