Thursday, July 9, 2009

In C# how do i construct a label using code from a class file? Read details please?

Below I have posted the construct for my class and the code where i create the label. When ever i construct this inside my Form1 i never see the label.





public Buddy(String sam)


{


Label bob = new Label();


bob.Location = new Point(100, 100);


bob.Size = new Size(40, 40);


bob.Text = "COOL!";


bob.Visible = true;


bob.Show();





}

In C# how do i construct a label using code from a class file? Read details please?
this is how i did it:


however, this one was an array of text boxes


txtFieldName[rowsNumber] = new TextBox();


txtFieldName[rowsNumber].Location = new Point(30, startLocationY);


txtFieldName[rowsNumber].Width = 80;


this.Controls.Add(txtFieldName[rowsNum...





oo i c what ur missing:


this.Controls.Add(bob)


if it worked chose as best answer :)
Reply:All the code is correct, except that you are missing the line to really add the control (label in this case) to the controls collection of the form. Each visible control must be part of this control collection. Only form, panel and groupbox have this controls collection since they are the only containers in .Net.





So the code is ... this.Controls.Add(bob);





'this' refers to the form, if you have a groupbox replace this with the groupbox object instance. You may also remove bob.Show(); code, that is not really need it.





bob.Visible = true; also can be removed since by default the control is visible so it can be safely removed.


No comments:

Post a Comment