locked
label creation RRS feed

  • Question

  • so i created a method which creates a label in form2 and called this method from form1 but i dont know what the label name will be. Could you please help me?


    Friday, December 5, 2014 2:30 PM

Answers

  • The method you wrote to create the label can give it a name. You will know what name you give it, it might always be the same name, or the name might be one of the arguments you pass to the method that creates it.

    If that doesn't help, please post the code for the method that creates the label and the method that needs to know the name of the label. Be sure to indicate which form each method is part of.

    [Edit] Your question doesn't seem to have anything to do with reading bodies. It is better to use a title for your thread that tells us what the question is about.
    • Edited by Blackwood Friday, December 5, 2014 2:54 PM
    • Proposed as answer by Carl Cai Thursday, December 11, 2014 3:14 AM
    • Marked as answer by Carl Cai Monday, December 15, 2014 7:53 AM
    Friday, December 5, 2014 2:53 PM
  • Maybe does it help if you show that method. 

    However, moreover, it is completely non OOP coding. It looks like a kind of Visual Basic style programming some programmers did before 1990.

    A Parent class should never change a child class beside inside the constructor.


    Success
    Cor

    • Proposed as answer by Carl Cai Thursday, December 11, 2014 3:14 AM
    • Marked as answer by Carl Cai Monday, December 15, 2014 7:53 AM
    Friday, December 5, 2014 3:15 PM

All replies

  • The method you wrote to create the label can give it a name. You will know what name you give it, it might always be the same name, or the name might be one of the arguments you pass to the method that creates it.

    If that doesn't help, please post the code for the method that creates the label and the method that needs to know the name of the label. Be sure to indicate which form each method is part of.

    [Edit] Your question doesn't seem to have anything to do with reading bodies. It is better to use a title for your thread that tells us what the question is about.
    • Edited by Blackwood Friday, December 5, 2014 2:54 PM
    • Proposed as answer by Carl Cai Thursday, December 11, 2014 3:14 AM
    • Marked as answer by Carl Cai Monday, December 15, 2014 7:53 AM
    Friday, December 5, 2014 2:53 PM
  • Maybe does it help if you show that method. 

    However, moreover, it is completely non OOP coding. It looks like a kind of Visual Basic style programming some programmers did before 1990.

    A Parent class should never change a child class beside inside the constructor.


    Success
    Cor

    • Proposed as answer by Carl Cai Thursday, December 11, 2014 3:14 AM
    • Marked as answer by Carl Cai Monday, December 15, 2014 7:53 AM
    Friday, December 5, 2014 3:15 PM
  • Okay i fixed it but now i've got another issue. I have created the CreateLabel method in Form2(Form2 is List in my case):

      public partial class List : Form
        {
             public List() 
        {
          InitializeComponent();
        }



             public void CreateLabel(string text, string name, int Width, int Height)
             {
                 Label label = new Label();
                 label.Text = text;
                 label.Name = name;
                 label.Location = new Point(Width, Height);
                 this.Controls.Add(label);
             }
        }                                                                                                                                         

    And then succesfully called that method from Form1:

    List list = new List();

                int[] labelWidth = new int[3];
                int[] labelHeight = new int[5];



                labelWidth[0] = 40;
                labelWidth[1] = 120;
                labelWidth[2] = 200;

                labelHeight[0] = 28;
                labelHeight[1] = 71;
                labelHeight[2] = 114;
                labelHeight[3] = 157;
                labelHeight[4] = 200;




                labelHeightNum++;

                if (labelHeightNum>4)
                {
                    labelWidthNum++;
                }

                if (labelHeightNum == 5)
                {
                    labelHeightNum = 0;
                }

                if (labelWidthNum == 3)
                {
                    MessageBox.Show("ERROR, all slots for cars in your list are being used, please delete one to continue.");
                }

                int labelNameNumber = 1;
                string labelName = String.Format("lblCar" + labelNameNumber);
                string labelText = String.Format("Custom Car " + labelNameNumber);

                list.CreateLabel(labelText, labelName, labelWidth[labelWidthNum], labelHeight[labelHeightNum]);





               labelNameNumber++;

    }

    But when i open list:

                

    private void btnList_Click(object sender, EventArgs e)
            {

                list.Show();
            }

    There is no label... 

    What is happening?

    EDIT: I am a beginner so my question might be dumb and the answer might be obvious...
    • Edited by tellyellinas Saturday, December 6, 2014 10:18 AM
    Saturday, December 6, 2014 10:15 AM
  • I see two possible problems.

    1. The code for posted from Form1 only creates one label. Perhaps the code is really part of a loop that will create all 15 labels. It would be helpful if you posted more of the code.
    2. The code you posted from Form1 creates a new List object (called list). If that statement is in the same method (perhaps Form1's Load event handler) as the code that creates the labels, then list will exist only withing that method and not in the Click event handler for btnList. Perhaps you declared list outside of any method so that it is available in any method in the class. Again, it would help if you post more of your code.

    I wrote to following to demonstrate that all 15 labels can be created. It does create them, although (at least on my system) you will need to increase the 2nd and 3rd values in labelWidth to avoid having the labels overlap.

            private void button1_Click(object sender, EventArgs e)
            {
                List list = new List();
    
                int[] labelWidth = {40, 120, 200};
                int[] labelHeight = {28, 71, 114, 157, 200};
    
                int labelNameNumber = 1;
    
                for (int h = 0; h <= 4; h++)
                {
                    for (int w = 0; w <= 2; w++)
                    {
                        string labelName = "lblCar" + labelNameNumber.ToString();
                        string labelText = "Custom Car " + labelNameNumber.ToString();
                        list.CreateLabel(labelText, labelName, labelWidth[w], labelHeight[h]);
                        labelNameNumber++;
                    }
                }
    
                list.Show();
            }

    Saturday, December 6, 2014 1:01 PM
  • Thanks for your reply! What I want to do is create 1 label at the click of the button, then if it is clicked again make another label. However I didn't test your code because I am on my tablet. I will provide you with the rest of the code probably within 10 minutes.

    Saturday, December 6, 2014 3:50 PM
  • Well, now being on my PC, i , with a bit experimenting fixed this problem as well. What the cause was is that i had 2 List list = new List(); 1 on the class itself and one on the button click. Anyway, yet again, now there is another problem. I run the app, everythings fine, i open the list once, everythings fine, and when i try to open it for the second time, boom, Cannot access a disposed object. Here is the code: But, i know the code itself is bad, missorganised and stuff, and since i'm a beginner, i wouldnt say no to critisism on how i can improve it, as long as it is not offensive :D 

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
     
    namespace MyApp
    {
       
        public partial class Form1 : Form
        {

            List list = new List();

            public Form1()
            {
                InitializeComponent();
            }

            int labelWidthNum = 0;
            int labelHeightNum = 0;
            
            string[] myArr = new string[999];

            private void btnCreateNewCar_Click(object sender, EventArgs e)
            {
                int i = 0;
                
                if(i < 999)
               {
                   string userSpecs = String.Format("Name: {0}" + Environment.NewLine + "Maker: {1} " + Environment.NewLine + "Model: {2} " + Environment.NewLine + "Creation Year: {3} " + Environment.NewLine + "Color: {4}", Name.Text.ToString(), Maker.Text.ToString(), Model.Text.ToString(), Year.Text.ToString(), Color.Text.ToString());
                    myArr[i] = userSpecs;
               }

                string createNewCar = String.Format("Congratulations, you have created a new car named: {0}" + Environment.NewLine + "Its specifications are:" + Environment.NewLine + "Maker: {1} " + Environment.NewLine + "Model: {2} " + Environment.NewLine + "Creation Year: {3} " + Environment.NewLine + "Color: {4}", Name.Text.ToString(), Maker.Text.ToString(), Model.Text.ToString(), Year.Text.ToString(), Color.Text.ToString());
                MessageBox.Show(createNewCar);

                 
                
                int[] labelWidth = new int[3];
                int[] labelHeight = new int[5];

                    

                labelWidth[0] = 40;
                labelWidth[1] = 120;
                labelWidth[2] = 200;

                labelHeight[0] = 28;
                labelHeight[1] = 71;
                labelHeight[2] = 114;
                labelHeight[3] = 157;
                labelHeight[4] = 200;

                           
                

                labelHeightNum++;

                if (labelHeightNum>4)
                {
                    labelWidthNum++;
                }

                if (labelHeightNum == 5)
                {
                    labelHeightNum = 0;
                }

                if (labelWidthNum == 3)
                {
                    MessageBox.Show("ERROR, all slots for cars in your list are being used, please delete one to continue.");
                }
                
                int labelNameNumber = 1;
                string labelName = String.Format("lblCar" + labelNameNumber);
                string labelText = String.Format("Custom Car " + labelNameNumber);
                
                list.CreateLabel(labelText, labelName, labelWidth[labelWidthNum], labelHeight[labelHeightNum]);
                

                
                
                    
               labelNameNumber++;
            }

            private void btnList_Click(object sender, EventArgs e)
            {
                
                list.Show();
            }

                
         }
            




        }

    Saturday, December 6, 2014 4:11 PM
  • Thanks for your reply! What I want to do is create 1 label at the click of the button, then if it is clicked again make another label. However I didn't test your code because I am on my tablet. I will provide you with the rest of the code probably within 10 minutes.

    If you want to create a new label each time you click a button, make sure that you are not defining labelHeightNum and labelWidthNum in the button's Click event handler, or if you do it should be Shared, otherwise they will be reset to zero every time you click the button.
    Saturday, December 6, 2014 4:13 PM
  • Any answer for my problem mentioned above?

    Saturday, December 6, 2014 10:38 PM
  • When you close the list form, you are disposing it and its resources, which is why you get that error when you try to show it again. You could try Hiding the list form instead of closing it. Or perhaps you should use ShowDialog instead of a Show to show the list form.

    list.ShowDialog();


    • Edited by Blackwood Sunday, December 7, 2014 12:58 AM
    Sunday, December 7, 2014 12:57 AM
  • Hi tellyellinas,

    The reply from Blackwood is helpful, and if you want to try to hide the list form, you could try the FormClosing event in the List Form.

    The code as below:

            private void List_FormClosing(object sender, FormClosingEventArgs e)
            {
                if (e.CloseReason == CloseReason.UserClosing)
                {
                    e.Cancel = true;
                    this.Hide();
                }            
            } 

    If you have any further questions, please feel free to post in this forum.

    Best Regards,

    Leo

    Monday, December 8, 2014 7:52 AM
  • Thanks you both for your replies as they both helped me! Everything is working now. What i want to do now is make these labels clickable. I really do not hae any idea how to do that, because the labels are created when the program is running, so i cant just go  to the list design and double click them and add my code. Any ways to do that?
    Monday, December 8, 2014 1:55 PM
  • Thanks you both for your replies as they both helped me! Everything is working now. What i want to do now is make these labels clickable. I really do not hae any idea how to do that, because the labels are created when the program is running, so i cant just go  to the list design and double click them and add my code. Any ways to do that?

    When you create the label, you can add an event handler for any of the labels events. For example, this code creates a label and adds a handler for the Click event.

    Dim lab As New Label
    lab.Text = "Some text"
    Me.Controls.Add(lab)
    AddHandler lab.Click, AddressOf LabelClick

    You then need to code the event handler in the form's class

    Private Sub LabelClick(sender As Object, e As EventArgs)
        Dim myLabel As Label = CType(sender, Label)
        'myLabel now references the label that was clicked 
    End Sub

    You can use the same event handler for several labels, the code above uses the "sender" argument to get a reference to the label that was clicked.

    Monday, December 8, 2014 4:04 PM
  • Okay but where exactly do i write this code? In the CreateLabel method in List(list is the form that displays the labels)? Just inside List? or inside Form1?
    Monday, December 8, 2014 6:09 PM
  • Okay but where exactly do i write this code? In the CreateLabel method in List(list is the form that displays the labels)? Just inside List? or inside Form1?

    You need to add the AddHandler statement to the CreateLabel method in List and the LabelClick Sub should be in the List Class. I just realised that you are coding in C# and I gave you VB code, here is the C# equivalent.

    To add a handler to a label you created (this code goes in CreateLabel)

    label.Click += LabelClick;

    The code for the click event handler (goes in the List class)

    private void LabelClick(object sender, EventArgs e)
    {
    	Label myLabel = (Label)sender;
    	//myLabel now references the label that was clicked 
    }


    • Edited by Blackwood Monday, December 8, 2014 8:20 PM
    Monday, December 8, 2014 8:19 PM
  • Thanks! I know i am being boring but i have another question. It will probably be the last one ill make. What i want to do is when these labels are clicked it opens a messagebox with the specifications of each car. I tried to do that by changing the code at List.cs to this: 

    string carLabelMessageBox = string.Empty;
    
             public void CreateLabel(string text, string name, int Width, int Height, string carName, string carMaker, string carModel, string carYear, string carColor)
             {
                 Label label = new Label();
                 label.Text = text;
                 label.Name = name;
                 label.Location = new Point(Width, Height);
                 this.Controls.Add(label); 
                 carLabelMessageBox = String.Format("Name: {0}" + Environment.NewLine + "Maker: {1}" + Environment.NewLine + "Model: {2}" + Environment.NewLine + "Creation Year: {3}" + Environment.NewLine + "Color: {4}", carName, carMaker, carModel, carYear, carColor);
                 label.Click += LabelClick;
             }
    
             private void LabelClick(object sender, EventArgs e)
             {
                 Label myLabel = (Label)sender;
                 MessageBox.Show(carLabelMessageBox);
             }

    So now, imagine there is 1 label created, when i click on it everything displays perfectly. I create a second label, click on it and it displays the correct specifications again. But, if i click the first label now, it shows me the specifications of the second(latest) label. I know the cause is because each time the MessageBox.Show(carLabelMessageBox); is executed, it executes with the latest carName, carMaker etc. strings. Any way i can do that?

    EDIT: forgot to mention that the strings in the parameters (carName, carModel etc.) are assigned to txtName.Text.ToString(), Model.Text.ToString() etc. which are the textboxes in Form1

    Tuesday, December 9, 2014 2:50 PM
  • Any Answer? 

    Wednesday, December 10, 2014 12:37 PM
  • Thanks! I know i am being boring but i have another question. It will probably be the last one ill make. What i want to do is when these labels are clicked it opens a messagebox with the specifications of each car. I tried to do that by changing the code at List.cs to this: 

    string carLabelMessageBox = string.Empty;
    
             public void CreateLabel(string text, string name, int Width, int Height, string carName, string carMaker, string carModel, string carYear, string carColor)
             {
                 Label label = new Label();
                 label.Text = text;
                 label.Name = name;
                 label.Location = new Point(Width, Height);
                 this.Controls.Add(label); 
                 carLabelMessageBox = String.Format("Name: {0}" + Environment.NewLine + "Maker: {1}" + Environment.NewLine + "Model: {2}" + Environment.NewLine + "Creation Year: {3}" + Environment.NewLine + "Color: {4}", carName, carMaker, carModel, carYear, carColor);
                 label.Click += LabelClick;
             }
    
             private void LabelClick(object sender, EventArgs e)
             {
                 Label myLabel = (Label)sender;
                 MessageBox.Show(carLabelMessageBox);
             }

    So now, imagine there is 1 label created, when i click on it everything displays perfectly. I create a second label, click on it and it displays the correct specifications again. But, if i click the first label now, it shows me the specifications of the second(latest) label. I know the cause is because each time the MessageBox.Show(carLabelMessageBox); is executed, it executes with the latest carName, carMaker etc. strings. Any way i can do that?

    EDIT: forgot to mention that the strings in the parameters (carName, carModel etc.) are assigned to txtName.Text.ToString(), Model.Text.ToString() etc. which are the textboxes in Form1

    Hello,

    Glad that you have solved your original issue, and honestly, I would recommend you post your another issue in new thread, it will help you get that issue focused by the other communities more efficiently.

    Thanks for your understanding.

    Regards.

    Carl


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    Thursday, December 11, 2014 3:16 AM