0

I have a textbox and button on c# form and users can enter number.I create a label which users want and each label have a button.Here if I click those buttons i wanna create textbox but if users continue to click,i want to create more textbox.

Button[] Btn= new Button[10];
for (int i = 0; i < labelNumber; i++)
{
    Btn[i] = new Button();
    Btn[i].Text = "Add";
    Btn[i].Location = new Point(40, 100 + i * 29);
    Btn[i].Size = new Size(50,20);
    this.Controls.Add(Btn[i]);
    Btn[i].Click += new EventHandler(addNewTextbox); 
}

on the code above; for example; if labelNumber == 3 so i have 3 label and 3 button with them, if i click add button i wanna create textbox near thislabel.

private void addNewTextbox(object sender, EventArgs e)
{
    TextBox[] dynamicTextbox = new TextBox[10];
    Button dinamikButon = (sender as Button);
    int yLocation = (dinamikButon.Location.Y - 100) / 29;
    //int xLocation =  dinamikButon.Location.X - 100;
    dynamicTextbox[yLocation] = new TextBox();
    dynamicTextbox[yLocation].Location = new Point(100, 100 + yLocation * 29);
    dynamicTextbox[yLocation].Size = new Size(40, 50);
    this.Controls.Add(dynamicTextbox[yLocation]);

}

here i change textbox y coordinates but i couldn't it for X. if i change this

dynamicTextbox[yLocation].Location = new Point(100*x, 100 + yLocation * 29);
x++;

it sort equals all of them.

Label1 Button1
Label2 Button2
Label3 Button3

if i click Button1 4 times,it has to create 4 textbox alongside label1. and if i click Button2 2 times,it has to create 2 textbox alongside label2 Please Help ME.

2
  • what happens if user continue clicking one and the same button? is there any limit of how many textboxes can be created? Commented Nov 16, 2015 at 21:01
  • I wanna crete textbox.I dont think about that but 6 is enough. Label1 Button1 textBox1 textbox2 Textbox3 Label2 Button2 Label3 Button3 @IvanStoev Commented Nov 16, 2015 at 21:03

1 Answer 1

1

The simplest way is to keep a list containing the created textboxes in the button's Tag property like this

private void addNewTextbox(object sender, EventArgs e)
{
    var button = (Button)sender;
    var textBoxes = button.Tag as List<TextBox>;
    if (textBoxes == null)
        button.Tag = textBoxes = new List<TextBox>();
    var textBox = new TextBox();
    textBoxes.Add(textBox);
    textBox.Location = new Point(100 * textBoxes.Count, button.Top);
    textbox.Size = new Size(40, 50);
    this.Controls.Add(textBox);
}

This way you not only can add a new text box, but also can easily determine the created text boxes by each button at any time if needed.

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

Comments

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.