Search code examples
c#visual-studiotextboxautosize

Can't set AutoSize property to dynamically created TextBox C# VS 2017


I am creating TextBoxes at runtime and need them to have fixed width. However, as I expect some large inputs from the user, it is supposed to be multiline, increasing its height accordingly.

I've been able to set all sorts of properties, except AutoSize, which I believe I have to, because my TextBoxes aren't behaving as I want them to. When I type a large input, they keep everything in only one line, and as it has fixed length, it doesn't show the entire text.

C# won't let me do textbox1.Autosize = True;

Here's what I have so far:

   TextBox textBox1 = new TextBox()
    {
        Name = i.ToString() + j.ToString() + "a",
        Text = "",
        Location = new System.Drawing.Point(xCoord + 2, yCoord + 10),
        TextAlign = HorizontalAlignment.Left,
        Font = new Font("ArialNarrow", 10),
        Width = 30,
        Enabled = true,
        BorderStyle = BorderStyle.None,
        Multiline = true,
        WordWrap = true,
        TabIndex = tabIndex + 1
    };

How do I set the Autosize property to a dynamically created TextBox?

Or is there another way to accomplish what I'm trying to?


Solution

  • You can try the following code to make the expected textbox.

        public partial class Form1 : Form
        {
        public Form1()
        {
            InitializeComponent();
        }
    
        private const int EM_GETLINECOUNT = 0xba;
        [DllImport("user32", EntryPoint = "SendMessageA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
        private static extern int SendMessage(int hwnd, int wMsg, int wParam, int lParam);
    
        private void Form1_Load(object sender, EventArgs e)
        {
    
            TextBox[,] tb = new TextBox[10, 10];
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    var txt = new TextBox();
                    tb[i, j] = txt;
                    tb[i, j].Name = "t";
                    tb[i, j].Multiline = true;
                    tb[i, j].WordWrap = true;
                    tb[i, j].TextChanged += Tb_TextChanged;
                    Point p = new Point(120 * i, 100 * j);
                    tb[i, j].Location = p;
                    this.Controls.Add(tb[i,j]);
                }
    
            }            
        }
    
        private void Tb_TextChanged(object sender, EventArgs e)
        {
            TextBox textBox = (TextBox)sender;
            var numberOfLines = SendMessage(textBox.Handle.ToInt32(), EM_GETLINECOUNT, 0, 0);
            textBox.Height = (textBox.Font.Height + 2) * numberOfLines;
        }
    }
    

    Result: enter image description here