Thursday, December 6, 2007

Refresh Schema on GridView doesn't work with Custom Objects

Let's say you have a custom object (instead of a DataSet or DataTable). You use this custom object for an ObjectDataSource and bind it to a GridView. You try to autogenerate the columns or Refresh Schema menu item and it doesn't work either. It says it can't do it. What do you do. Chances are that in your Get / Select method in your custom object you are returning something like an array. The easiest way is to instead use the List generic collection. In most cases it is a better performer and better choice than an ArrayList, but is type safe, and have the same basic features. For more details, see on which one you should use. In our case, we need to use the List generic collection so that the GridView can get the columns from it. If you wanted to create your own collection (why I don't know) you could probably do something like is described in this blog ( Please note, I have not tried this nor do I want to. It looks way to complicated for something that should be so basic! Granted the problem they are trying to solve is a more complex, but I am willing to bet the needed interfaces are the same. With that said, here is an example of how you might use a generic List instead of an ArrayList. public List<PersonEntity> FetchPersonGetAll() { SqlDataReader reader = null; List<PersonEntity> entities = new List<PersonEntity>(); try { reader = daab.ExecuteReader("up_FetchPersonGetAll"); while (reader.Read()) { entities.Add(FillEntityFromReader(reader)); } } catch (Exception ex) { throw ex; } finally { // close reader and connection here } return entities; }

No comments: