无法将 AutoSize 属性 设置为动态创建的 TextBox C# VS 2017

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

我在运行时创建文本框,需要它们具有固定宽度。但是,正如我期望用户输入大量内容一样,它应该是多行的,相应地增加了它的高度。

我已经能够设置所有种类的属性,除了 AutoSize,我相信我必须这样做,因为我的 TextBoxes 没有按照我希望的方式运行。当我输入大量内容时,它们将所有内容都保留在一行中,并且由于它具有固定长度,因此不会显示整个文本。

C# 不允许我这样做 textbox1.Autosize = True;

这是我目前的情况:

   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
    };

如何将自动调整大小 属性 设置为动态创建的文本框?

或者是否有其他方法可以完成我正在尝试的事情?

您可以尝试使用以下代码制作预期的文本框。

    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;
    }
}

结果: