Click here to Skip to main content
15,889,096 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How would i move a dynamically added text box after the program has started?
I would like the person that uses the program to be able to move it.
and here is the code that i'm using to put in a text box.
C#
private void button1_Click(object sender, System.EventArgs e)
{
    TextBox textbox1 = new TextBox();
    textbox1.Location = new Point(25, 25);
    this.Controls.Add(textbox1);
}


p.s. will the code above give me infinite amounts of text boxes because that's kinda what i want.

sorry to SA for not wording the question right.
Posted
Updated 27-Mar-12 12:54pm
v2
Comments
Sergey Alexandrovich Kryukov 27-Mar-12 17:42pm    
Why do you think a text box could be created "before runtime"?
--SA

Modify you button click Event as below

C#
TextBox textbox1 = new TextBox();
textbox1.Name = "Txt1";// this is useful to identify the object
textbox1.Location = new Point(25, 25);
this.Controls.Add(textbox1);


Then add this code to where you want to move the text box

C#
foreach (Control item in this.Controls)
{
    if (item is TextBox && item.Name == "Txt1")
        item.Location = new Point(90, 90);//this is the x,y coordination to new location
}
 
Share this answer
 
You move it in exact same way: myTextBox.Location = new Point(/* .. */); or myTextBox.Left = /* ... */; myTextBox.Top = /* ... */. No invalidation is required, as it is all implemented in the property setters.

You understanding or design time is wrong: all controls are created during run-time. The designer is something working in the Visual Studio design time; it only helps to write code which actually is executed during your application's run-time. To make sure, just take a look at the auto-generated C# code. By the way, this is also a simple way of learning how to write some code if you only know how to do it with the designer: look at the auto-generated file and see.

—SA
 
Share this answer
 
v2
Comments
Wonde Tadesse 27-Mar-12 19:16pm    
5+. Correct
Sergey Alexandrovich Kryukov 27-Mar-12 19:25pm    
Thank you, Wonde.
--SA
Thilina Chandima 28-Mar-12 1:31am    
i think the problem is he can't access the object from outside the button click event because it is local to that block.
Sergey Alexandrovich Kryukov 28-Mar-12 21:29pm    
Thank you for this note.

Of course, there would be no direct access to it; the problems is that the code is weird: it will add a control in the same location, on every click. Probably OP needs the closure; with output position parameter shifting on every click. As I don't see much sense in it, I don't want to get into further detail; maybe OP will ask me.
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900