在我的 .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(使用前将#替换为@)