I have a for loop which calls click event every time. I want to append some string to the function name. say, button_click then I want it to be Button_click1, Button_click2 etc..
I want to perform some operation on values 1, 2 etc.. Please suggest if there is any other way to access this information.
Thread can be the last option I would opt.
The other answers are more correct for my money, but If you really need string based invocation I think you'll need to use the Reflection classes.
String suffix = "_Click1";
Type myType = typeof(MyClass);
myType.InvokeMember("Button"+ suffix,
BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod, null, yourButtonObject, null);
You can try to create a Button array in and then you can create an event for a click of any button in the array.
Than, You can use a for loop that closes over a variable containing the current index:
for(int i = 0; i < buttons.Length; i++)
{
//it's important to have this; closing over the loop variable would be bad
int index = i;
buttons[i].Click += (sender, args) => SomeMethod(buttons[index], index);
}
This probably would be going to save a lot lines of code and easier as well.
I think you should just put all buttons in a list like so:
List<Button> ButtonList = new List<Button>(){Button1, Button2};
And then just call Button_Click for each of those buttons like so:
Foreach(Button button in ButtonList)
button.Button_Click(this, new EventArgs());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.