Search code examples
.netcomboboxclrironpython

Python.NET WinForms - Loop through each combobox


What is the best solution to loop through each combobox (I have four) and grab it's text?

Some documentation (via c#) says to create a list of comboboxes but I am not sure how to port that over to Pyhton via the .NET Framework. Everything I've done seems to generate some error.

I could loop through all the controls but research states that it it not necessary and burns up CPU time.

With all that said, here is what I have done so far without success. I've taken out other parts of the code to just focus in on this:

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")
clr.AddReference("System.Data")
clr.AddReference("System.Globalization")
clr.AddReference("System.Collections")

from System.Windows.Forms import *
from System.Drawing import *
from System.Data import *
from System.Data.SqlClient import *
from System.Globalization import *
from System.Collection.Generics import *

    def FindPopulatedDropDowns():
        # https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1?view=net-5.0
        Items = List[string]()
        
        comboBoxes = OfType[ComboBox]().Where(x in x.Name.StartsWith('comboBox'))
        
        for cmb in comboBoxes:
            for cmbitem in cmb.Items:
                print(cmbitem.ToString())

Anyone have any ideas on how to accomplish this?


Solution

  • Here is my solution. I am sure there are more elegant ways, but this works for my needs.

        def FindPopulatedDropDowns(self):
            
            # https://learn.microsoft.com/en-us/dotnet/api/system.object.gettype?view=net-5.0#System_Object_GetType
            for c in self.Controls:
                if c.GetType() == ComboBox:
                    print(c.Text)