[IronPython] Binding a Python class to a DataGridView

David McWright david.mcwright at usbfmi.com
Thu Feb 25 03:16:42 CET 2010


I'm working with DataGridView in IPY2.6.1 and I'm having trouble with
a couple of things.  I found a closed issue on the CodePlex here:

http://www.codeplex.com/IronPython/WorkItem/View.aspx?WorkItemId=6332

and used it as a platform to experiment.  I've attached the code to
this post below.  However, the changes I have made led me to a couple
of issues:
1) If I set the DataSource of the DataGridView(DGV) to a BindingList
containing instances of a custom class, then the DGV adds a column for
both properties and instance variables.  Obviously, the DGV doesn't
discriminate, is there a way that I can make it add only properties?
2) The purpose of using the BindingList was to facilitate deletion,
editing and adding new records to the DGV.  Deletion and editing work
fine, but trying to add a new record causes a run-time error
"System.MissingMethodException: Constructor on type
'IronPython.NewTypes.System.Object_1$1' not found."  Any ideas why
this is?  Is there a better way to bind a collection, list, etc to a
DGV than using a BindingList, an idea I got from a C# book?

import clr
import System

clr.AddReference('System.Windows.Forms')
import System.Windows.Forms as SWF
from System.ComponentModel import BindingList

SAMPLE_DATA = [
('Joe', 23),
('Bob', 8),
('Thomas', 32),
('Patrick', 41),
('Kathy', 19),
('Sue', 77),
]


class Person(System.Object):

    def __init__(self):
        self._name = ""
        self._age = -1

    def get_name(self):
        return self._name

    def set_name(self, value):
        self._name = value

    Name = property(get_name, set_name)

    def get_age(self):
        return self._age

    def set_age(self, value):
        self._age = value

    Age = property(get_age, set_age)

class DBInterface:
    @staticmethod
    def GetPairs():
        Pairs = BindingList[Person]()
        Pairs.AllowNew = True
        for name, age in SAMPLE_DATA:
            temp = Person()
            temp.Name = name
            temp.Age = age
            Pairs.Add(temp)
        return Pairs


class Form(SWF.Form):

    def __init__(self):
        SWF.Form.__init__(self)

        grid = SWF.DataGridView()
        grid.AutoGenerateColumns = True

        grid.DataSource = DBInterface.GetPairs()

        grid.Dock = SWF.DockStyle.Fill
        self.Controls.Add(grid)

SWF.Application.EnableVisualStyles()
form = Form()
SWF.Application.Run(form)

Thanks,
David



More information about the Ironpython-users mailing list