Skip to content

Multiple textboxes created dynamically

andre prins

Asked Feb 20, 2009, 10:20 AM EST1 answer
Share
LinkedInX

 I have my roots in pascal like languages and just recently started in c# and OOP
I can manage my way around, but I just am missing a key point, so I hope you can help me.

ps. I am using Microsoft Visual C# 2008 expressedition

I was building a text editor as an exercise.
I do not create the textbox at design time, but do it dynamically when I click the menu option, open file.
so far all fine. I also created a menustrip and items among which "window" and when I click open, the filename that I open is added to the menustrip under window

So : the textwindow is opened by the method below:

C#
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
      openFileDialog1.InitialDirectory = @"d:\";
      openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
       DialogResult myfile = openFileDialog1.ShowDialog();
      TextBox txt = new TextBox();
      txt.Multiline = true;
      txt.Location = new Point(5, 25);
      txt.Width = this.Width -20;
      txt.Height = this.Height - 64;
      txt.Lines = File.ReadAllLines(openFileDialog1.FileName);
      Controls.Add(txt);
      this.windowToolStripMenuItem.DropDownItems.Add(openFileDialog1.FileName);
}

this works OK for the first txt file I open, but if I then open another file, it does show up under window as a second entry, but the textbox itself is not showing up....

and my other issue is, txt is unknow to other methods. so say I click on one of the entries under window how do I know which txt window to make the "active" window ?
I would assume to make a class that holds the window handle, filename and maybe more and then an array of this class. every array[1] contains a copy of this class so I can relate an entry from the "window" drop down to a handle, but how can every method access this array (or whatever you would suggest to create)

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    You could create the txtclass and assign to the collections object as you've thought of, though I'd go for the List<T> i.e. List<TextBox>
    However, you seem to have a couple of other problems. You've set a fixed location for you textbox and so all others sit on the same location.
    Unless you find a way of automatically incrementing the Y location with each click. The same could apply with naming the control.
    To have a better layout, try using containers such as TableLayout, FlowLayout or Tab. I guess tab might work well as each editor
    will open in its own tab window. Once you've separated them, you'll have other options of accessing your control apart from placing it in a collection.
    0