【发布时间】:2015-02-04 09:10:01
【问题描述】:
我想这样声明一个按钮:private: System::Windows::Forms::Button^ NewButton;,然后像这样制作 11 个相同的按钮:
int Loc=0;
for(int i=1;i<12;i++)
{
this->NewButton = (gcnew System::Windows::Forms::Button());
this->NewButton->BackColor = System::Drawing::Color::White;
this->NewButton->FlatStyle = System::Windows::Forms::FlatStyle::Flat;
this->TheList->Controls->Add(this->NewButton);
this->NewButton->Location = System::Drawing::Point(-1,Loc-1);
this->NewButton->Size = System::Drawing::Size(200, 30);
this->NewButton->TabIndex = i;
this->NewButton->Text = L"hej"+i;
this->NewButton->Name = L"Button"+i;
this->NewButton->Click += gcnew System::EventHandler(this, &Form2::NewButton_Click);
Loc+=29;
}
private: System::Void NewButton_Click(System::Object^ sender, System::EventArgs^ e) {
NewButton->Text = "Hello";
}
现在我按下切换按钮来启动事件并不重要,但只有最后一个按钮更改了它的文本。有没有办法让按钮用一个数字或它的名字来调用?如果不是,请提供替代解决方案。
【问题讨论】:
-
您只跟踪一个按钮,NewButton 变量存储它。只需将其类型更改为
List<Button^>^,您就可以跟踪所有这些。或者更好的是,不要打扰,因为没有必要,在 Click 事件处理程序中使用safe_cast<Button^>(sender)。 -
非常感谢 ;) 真的很有帮助!