Windows Develop Bookmark and Share   
 index > Windows Forms Data Controls and Databinding > Binding a typesafe collection to a DataGrid
 

Binding a typesafe collection to a DataGrid

There have been very similar posts before, but none help with this particular problem.

If I define a typesafe collection like this simplified version of the actual code

    public class HighScore
    {
     public String Name;
     public Int32 Score;
    }

    public class HighScoreList: CollectionBase, IList
    {
      public HighScore this[Int32 index]
      {
        get{ return (HighScore)InnerList[index]; } 
        set{ InnerList[index] = value; }
      }

      public void Add(HighScore highScore)
      {
        InnerList.Add(highScore);
      }
    }

I would expect to be able to display the list in a DataGrid by assigning an object of type HighScoreList to it's DataSource property, but if I do this the grid displays the correct number of rows, but no columns of data at all.

I know I can work around this by adding the data to a DataSet first, but I want to understand why the above method does not work, and what to change to make it work as expected.
MigrationUser 1  Friday, May 30, 2003 3:56 PM
Now solved this myself. The answer is that the members of HighScore that you want to appear in the grid must be properties, and not just public data members.

In other words the first class must be rewritten as

public class HighScore
{
  private String name;
  private Int32 score;

  public String Name
  {
    get{ return name; }
    set{ value = name; }
  }

  public Int32 Score
  {
    get{ return score; }
    set{ value = score; }
  }
}

And then it all works perfectly.
MigrationUser 1  Monday, June 02, 2003 2:02 PM

You can use google to search for other answers

Custom Search

More Threads

• How do I set a DataGrid View
• New records bound to combobox not in sequence.
• Textbox And Capital Letters
• DataGridView IsCurrentRowDirty
• I've Butchered BindingList<T> FindCore - Help making Generic Comparison
• Controls not showing in additional form
• Filling StronglyTyped DataSets
• Alignment of a DataGridView Col bound to ArrayList that has objects
• datagrid click event is not firing
• NullReferenceException in Unknown Module when binding 2 checkboxes.