不管是用 WinForm 的 DataGrid 还是用 WebForm 的 DataGrid,当用 DataTable 作数据源时,可以通过
    DataRow row = myTable.Rows[i];
    object val = row["ColumnName"];
来得到一行记录中的指定字段的信息, DataGrid 应该也是通过传入一个列名的字符串来取得这个值进行显示。但是如果我用自定义的类的对象数组作数据源时,类中也提供类似于 DataRow 的索引方法:
public class Student{
public object this[String column]{
return ......;
}
//......
}
时,DataGrid 却报错说没有这个属性,它只认识已经定义好的 get 属性。这是为什么?

解决方案 »

  1.   

    但是如果我用自定义的类的对象数组作数据源时,类中也提供类似于 DataRow 的索引方法:
    public class Student{
    public object this[String column]{
    return ......;
    }不用上面的索引。只能绑定属性(get/set的那个),不能绑定字段!
      

  2.   

    但是为什么 DataRow 可以通过这种方式取值呢,这是我非常想知道的
      

  3.   

    DataBinder的Eval是使用PropertyDescriptor实现的,在常见的绑定中,记录是以DataRowView出现的,它实现了ICustomTypeDescriptor参考
    http://www.nikhilk.net/DataBindingToPublicFields.aspx
      

  4.   

    如果不继承任何接口的话,你用对象来形成Array或者ArrayList去绑定DataGrid,那么对于绑定而言要以类型的公有属性才能被识别。要想象DataTable一样,你需要把自己的类继承IListSource,来完成相应的接口。