private void buttonCheck(object sender, EventArgs e)
{
Type x = sender.GetType();
var y = Activator.CreateInstance(x); //sends me back to the original problem : sender is an object, not a usable object.
var x = (Button)sender; // == button, but you never know what sender is until it's already in this function... so
dynamic z = sender; //gives you the image of sender i'm looking for, but it's at runtime, so no intellisense/actual compiletime knowledge of what sender is.
}
how do you go about creating a usable instance of sender without prior knowledge of the class sender is actually bringing to this method?
Here's a DataBindingComplete variation that clears the default selection from the DataGridView control. I've got numerous DataGridView controls across multiple tabs and only need this one event handler for all of them which is fantastic. This is based off the response from VladL so all credit should go to them.
I think dynamic keyword is what you are looking for. At compile time compiler assumes that there is
Text
property in btn.In the vast majority of cases you know what control(s) will be firing the event because you (the programmer) wire them up. For example, if you wire this event up to a button (or even multiple buttons), You know the sender is a
Button
so you can just cast:or
either one will give you full intellisense.
If you wire up this event to multiple control types, your best bet is to check each possible type:
It may seem messy, but since you haven't stated what you actually want to do in the event handler that's the cleanest way in one event to handle multiple possible sender types.
Another option would be to just create multiple event handlers (one for each type) and wire them up to their respective types. I can't think of many code-reuse scenarios between a
Button
and aTextBox
.