首页 > 解决方案 > 无法将 AutoSize 属性设置为动态创建的 TextBox C# VS 2017

问题描述

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

我已经能够设置各种属性,除了 AutoSize,我相信我必须这样做,因为我的 TextBox 的行为不像我想要的那样。当我输入一个大的输入时,它们只将所有内容保留在一行中,并且由于它具有固定长度,因此它不会显示整个文本。

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

如何将 Autosize 属性设置为动态创建的 TextBox?

还是有另一种方法来完成我想要做的事情?

标签: c#visual-studiotextboxautosize

解决方案


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

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

结果: 在此处输入图像描述


推荐阅读