为什么在 DataTable 上调用 AsEnumerable() 会阻止 GridView 与其绑定?

2023-12-24

在我的 .aspx 页面中,我有一个<asp:GridView runat="server" ID="CustomerGridView">控制我像这样绑定:

public partial class InsertCustomer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewCustomer();
        }
    }

    private void ViewCustomer()
    {
        var manager = new DomainManager();
        var result = manager.FindAll(new Customer());
        this.CustomerGridView.DataSource = result;
        this.CustomerGridView.DataBind();
    }
}

这里是DomainManager class:

public class DomainManager
{
    readonly StringBuilder _queryBuilder = new StringBuilder();
    private Type _entityType;
    readonly SQLHelper _sqlHelper = new SQLHelper();

    public IEnumerable FindAll<T>(T entity)
    {
        _entityType = entity.GetType();
        var query = string.Format("select * from {0}", _entityType.Name);
        var dt = _sqlHelper.FillDataTable(query);
        return dt.AsEnumerable();
    }
}

问题是我的网格没有正确绑定。为什么不?


尝试改变

return dt.AsEnumerable(); 

to

return dt.DefaultView;

解释:默认情况下,一个GridView绑定到对象的实际属性。例如,如果数据源是List<Customer>,然后你可以绑定到Name各自的财产Customer。但是当数据源是DataTable的客户,那么每个客户都由一个代表DataRow, and a DataRow does not have a Name财产GridView可以绑定到.

为了支持动态属性,对象必须实现ICustomTypeDescriptor界面。该接口的实现是DataRowView但不是DataRow。通过修改代码返回dt.DefaultView(这是一个DataView),您提供GridView与集合DataRowView它可以绑定到的对象。

现在你可能想知道为什么

this.CustomerGridView.DataSource = dt;

有效,但是

this.CustomerGridView.DataSource = dt.AsEnumerable();

doesn't.

原因是DataTable实施IListSource接口,它告诉GridView“不要用我作为数据源,用我的DefaultView相反。”但是AsEnumerable()返回一个未实现的包装对象IListSource, 所以GridView不知道如何到达DefaultView.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么在 DataTable 上调用 AsEnumerable() 会阻止 GridView 与其绑定? 的相关文章

随机推荐