Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I dynamically assign label control names through a loop?

Status
Not open for further replies.

t03

Programmer
Oct 25, 2008
1
0
0
US
The following is a sample code I am working on. I can dynamically create three labels and make them appear on the form.

I can even make them work exactly the same btn1_Click function. But, how can I dynamically assign the label names to each label, so I can use them to identify the labels and change their values.

#using <System.dll>
#using <System.Windows.Forms.dll>
#using <System.Drawing.dll>

using namespace System;
using namespace System::Drawing;
using namespace System::Windows::Forms;

public ref class Form1: public System::Windows::Forms::Form
{
public:

String^ a;

Form1() {

for (int i=0; i<=2; i++) {
Label^ a= gcnew Label;
a->Text = Convert::ToString(i);
a->Name = "btn"+Convert::ToString(i);
a->Size = Drawing::Size(25, 25);
a->Left = 10+i*30;
a->Top = 10;
this->Controls->Add(a);
Console::WriteLine(a->Name);
a->Click += gcnew System::EventHandler(this, &Form1::btn1_Click);
}

}

private: System::Void btn1_Click(System::Object^ sender, System::EventArgs^ e) {
btn2->Text ="Hi";
}


};

[STAThread]
int main() {
Application::Run(gcnew Form1);
}

 
A name in a compiled language is used by the compiler and doesn't have any real meaning at runtime; i.e., it's a compile-time entity. Since you are creating objects at run time, there isn't any way to create a fixed name. You can put the object into a variable, and then refer to it that way, like you're doing here (the variable named 'a') -- all you need to do is have names for each label. If you want to handle a variable number of labels, you could create an array, place each label into the array, and then refer to items as a[0], a[1], etc.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top