15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1134 ❘ ChaPTer 39 windOws fOrms<br />

ilistsource <strong>and</strong> ilist interfaces<br />

The DataGridView also supports any object that exposes one of the interfaces IListSource or IList.<br />

IListSource has only one method, GetList(), which returns an IList interface. IList, however, is<br />

somewhat more interesting <strong>and</strong> is implemented by a large number of classes in the runtime. Some of the<br />

classes that implement this interface are Array, ArrayList, <strong>and</strong> StringCollection.<br />

When using IList, the same caveat for the object within the collection holds true as for the Array<br />

implementation shown earlier — if a StringCollection is used as the data source for the DataGrid, the<br />

length of the strings is displayed within the grid, not within the text of the item as expected.<br />

Displaying Generic Collections<br />

In addition to the types already described, the DataGridView also supports binding to generic collections.<br />

The syntax is just as in the other examples already provided in this chapter — simply set the DataSource<br />

property to the collection, <strong>and</strong> the control will generate an appropriate display.<br />

Once again, the columns displayed are based on the properties of the object — all public readable fields are<br />

displayed in the DataGridView. The following example shows the display for a list class defined as follows:<br />

class PersonList: List < Person ><br />

{<br />

}<br />

class Person<br />

{<br />

public Person( string name, Sex sex, DateTime dob )<br />

{<br />

_name = name;<br />

_sex = sex;<br />

_dateOfBirth = dob;<br />

}<br />

public string Name<br />

{<br />

get { return _name; }<br />

set { _name = value; }<br />

}<br />

public Sex Sex<br />

{<br />

get { return _sex; }<br />

set { _sex = value; }<br />

}<br />

public DateTime DateOfBirth<br />

{<br />

get { return _dateOfBirth; }<br />

set { _dateOfBirth = value; }<br />

}<br />

}<br />

private string _name;<br />

private Sex _sex;<br />

private DateTime _dateOfBirth;<br />

enum Sex<br />

{<br />

Male,<br />

Female<br />

}<br />

code snippet 03 MainExample/Person.cs<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!