Answers for "c# button click gets assigned the last value"

C#
0

c# button click gets assigned the last value

List<object> asd = new List<object>();

for (int i = 0; i < asd.Count; i++)
{  
  	// Let's say you are trying to create buttons
  	// Because the memory address gets overwritten
  	// the button will always use the last value looped
  	Button btn = new Button() { Click += SomeMethod(asd[i]) };
 
  	// This is crucial as this will reference
  	// a new memory address.
	object obj = asd[i];
  
  	// So do it like this
  	Button btn = new Button() { Click += SomeMethod(obj)};
  
  	// do something..
}
Posted by: Guest on March-22-2021

Code answers related to "c# button click gets assigned the last value"

C# Answers by Framework

Browse Popular Code Answers by Language