I wrote a C++ program using Borland C++ Builder 5. The program dynamically creates an array of TCheckBox
objects. I have tried to write an OnClick
event handler that would identify which checkbox is being clicked and execute some instructions based on that. My event handler is based on similar posts to this website, but I cannot seem to make it work.
Here is the (abbreviated) code
// Header declaration
void __fastcall CBoxClick(TObject *Sender);
// End Header
// CBoxClick function (the event handler)
void __fastcall CBoxClick(TObject *Sender){
if (dynamic_cast<TCheckBox*>(Sender)!=NULL){
//Do stuff
}
else{
Form1 -> Debug -> Text = "Object is not a TCheckBox";
}
}
void ChkBoxInit(void){
int i; //Loop counter index
TCheckBox* ChkBx[NCARDS]; //Define array of type checkboxes
for(i = 0; i < NCARDS; i++){ //Initalize each checkbox
ChkBx[i] = new TCheckBox(Form1); //Create a new checkbox
ChkBx[i] -> Parent = Form1; //Define parent of checkbox
ChkBx[i] -> Tag = i; //Set value of Tag to index
// Other CheckBox parameters here such as Height, Width, Top, Left, Name are here
// Next, call event handler. I've tried the following 2 statements with the comment results
ChkBx[i] -> OnClick = CBoxClick(ChkBx[i]); // Results in E2109: Not an allowed type
ChkBx[i] -> OnClick = CBoxClick; /* Alternate try - Results in E2034: Cannot convert
'void (_fastcall *)(TObject *)' to
'void (_fastcall * (_closure )(TObject *))(TObject *)' */
} //End of for loop
} //End of function
CBoxClick()
is not a member of your Form class.Within your cpp file, the compiler sees it as a standalone function. That is what the error message is complaining about when the assignment of the
OnClick
event fails (non-static class methods have the__closure
attribute, non-members do not).Make sure
CBoxClick()
is declared inside your Form class in the header file:And then change this line in your cpp file:
To this instead:
And then change your assignment of the
OnClick
event from this:To this instead (since
ChkBoxInit()
itself appears to not be a member of the Form class, either):The first syntax you tried (
OnClick = CBoxClick(ChkBx[i]);
) is just plain wrong, as you are actually callingCBoxClick()
and then trying to assign itsvoid
return value toOnClick
, which obviously will not work. You need to assign the address ofCBoxClick()
toOnClick
, and that will work only for non-static class methods, not for standalone functions (well, it CAN be done, but it requires different code involving a type-cast hack utilizing theTMethod
struct).Also, you should not be using
dynamic_cast
. Since you know theSender
will always be aTCheckBox
, usestatic_cast
instead:UPDATE: Now, with that said, a better option is to get rid of
ChkBoxInit()
altogether and do the array initialization inside the Form's own constructor instead: