Forum Discussion

marin's avatar
marin
Frequent Contributor
13 years ago

How to select a dynamically created button in Windows form

Hello all,



in my .NET Win Forms application, there is a scenario where a dynamic number of buttons will be created on a form.

I need to perform a click on a certain button.

Have tried the following (see attached screenshot for name mapping):







//attempt to access the record with index 5 and to click the button contained there:

var record = Aliases.TestApp.frmMain.MdiClient.frmOverview.pnlContainer.pnl.WinFormsObject("Record")[5];

var button = record.WinFormsObject("btn")[0];

button.Click();







but this wouldn't work...



What would be the correct approach?



Many thanks for any hints...
  • marin's avatar
    marin
    Frequent Contributor
    Hello all,



    found out how to access the first level object ("Record") via FindChild() method:





    var PropAray = new Array ("ClrClassName", "Index");

    var ValArray = new Array ("Record", 5)



    var _record = Aliases.TestApp.frmMain.MdiClient.frmOverview.FindChild(PropArray, ValArray);





    Variable record correctly holds the WinForm object "Record" (checked in Inspect window on debugging).

    But now I need to grab the button which is a child of that object and to perform click. So I was under impression that I could just further use the FindChild() method for instantiated and initialized local variable _record, but this does not seem to work (_record.FindMethod() seems not to be possible, also intellisense is not working after typing a dot after _record).



    Is it true, that FindChild() can not be used for local variable? What would be the correct approach to access that button which is child of "Record"?



    Many thanks...
  • marin's avatar
    marin
    Frequent Contributor
    Well...



    it is indeed possible to use FindChild() method if correct values are set in the property/value arrays ;-).

    It was wrong index value for the button I was searching for - if correct index is set, then everything works fine and button will be found.