0

I am currently using a loop to create a new User Control on my windows form. I want it to add a single instance of this User Control in a new position where Y is incremented by 125 each time.

I'm pretty new with C# and Visual Studio, so with the below code, the first instance is being replicated each time I press the 'add' event. I was just wondering if someone can give some assistance on the best way to store the value of 'y' from this first instance to be passed into the loop the second time? Or if there is any better way to do this.

Thanks in advance!

private void btnAddRow_Click(object sender, EventArgs e)
        {
        int y = 175;
        for (int i = 0; i <= 0; i++)
        {
            NewSkillRow nSkill = new NewSkillRow();
            nSkill.Location = new Point(75, y += 125);
            Controls.Add(nSkill);
            btnAddRow.Click += new EventHandler(btnAddRow_Click);
        }
        }
3
  • 1
    "with the below code" I don't see any code! Commented Apr 24, 2017 at 14:29
  • 1
    My bad! I've only just signed up today and didn't realise there was an add code tool on Ctrl + K! Commented Apr 24, 2017 at 14:30
  • there is no need for the loop. and y could be a variable local to the class. not the event handler, so it would keep its value between calls to btnAddRow_Click, and can be incremented there. also, it makes no sense to reattach the event handler in the handler - that is done only once in form initialization. Commented Apr 24, 2017 at 14:33

1 Answer 1

1

Make your y variable local to the class (you can also initialize it with its default):

private int y = 175;

The event handler is called every time you click the button. So remove the initialization of y from there.

private void btnAddRow_Click(object sender, EventArgs e)
{
    var nSkill = new NewSkillRow();
    nSkill.Location = new Point(75, y += 125);
    Controls.Add(nSkill);
}

Note that the event handler attachment was removed. Reattaching an event handler from within the handler would lead to an increasing number of invokations every time the button is clicked.

The loop is fine, but not necessary: For just one iteration, you can as well just omit it.

The use of the y += 125 is also ok, it relies on the specification that the return value of an assignment operator is the value that has been assigned.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! and for explaining it so clearly. I'm not so used to this C# way of things yet, I would of been scratching my head for a while!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.