【问题标题】:I want to stack buttons with the same name but be able to call them as individuals我想堆叠具有相同名称但能够将它们称为个人的按钮
【发布时间】: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&lt;Button^&gt;^,您就可以跟踪所有这些。或者更好的是,不要打扰,因为没有必要,在 Click 事件处理程序中使用 safe_cast&lt;Button^&gt;(sender)
  • 非常感谢 ;) 真的很有帮助!

标签: winforms button c++-cli


【解决方案1】:

NewButton 是一个实例变量,因此在循环的每次迭代中,您都将其替换为不同的实例 - 只能保存一个,所以这是最后一个。

在按钮被按下时的回调中,你会得到sender 作为参数,它应该是被按下的按钮。因此,您应该使用sender 来更新按钮上的文本,而不是使用NewButton

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2012-10-03
    • 1970-01-01
    • 1970-01-01
    • 2015-08-27
    • 1970-01-01
    • 2023-01-07
    相关资源
    最近更新 更多