Using variables to access objects in a windows form.

Alright, so I'm making a windows form with a few hundred buttons, and one button will change color based on data the program receives over a socket.

This is what I have, and it kind of works, but I don't want to have to make another if statement for all 260 buttons.

1
2
3
4
5
6
7
8
9
10
11
12
13
void hitmiss(std::string u){
	std::string^ ind = reccdata2();
	if (u == "button6"){
		if (ind == "1"){
			this->button6->BackColor = System::Drawing::Color::Red;
			this->textBox2->Text = L"hit";
		}
		if (ind == "0"){
			this->button6->BackColor = System::Drawing::Color::Blue;
			this->textBox2->Text = L"miss";
		}
}
}


What I want to do is make it more like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void hitmiss(System::String^ u){
	std::string^ ind = reccdata2();
	if (ind == "1"){
	this->u->BackColor = System::Drawing::Color::Red;
	this->textBox2->Text = L"hit";
	}
	if (ind == "0"){
	this->u->BackColor = System::Drawing::Color::Blue;
	this->textBox2->Text = L"hit";
	}
}

int main(){
	hitmiss(button6);
	return 0;
}

But it returns the error that u is not a part of Form1.
Last edited on
You don't really have a choice if this->button1 to this->button260 are all independent members. You would be able to iterate if you instead had this->button[0] to this->button[259].
Could you give an example of how that would work? The way I understood you, I thought I could have a button named "button[1]" and then do

this->button[u]->BackColor = System::Drawing::Color::Blue;

But "button[1]" is an invalid name
Last edited on
You need to declare an array of buttons in the class, obviously.
Topic archived. No new replies allowed.