如何将文本框中的条目长度限制为其宽度

时间:2010-07-29 11:49:44

标签: c# textbox

C#: 默认情况下,文本框接受n个条目,

我想将条目限制为宽度

文本框中是否有任何属性可供我使用,

5 个答案:

答案 0 :(得分:1)

默认只接受32767个字符。

您可以在MaxLength

中设置文本框的textbox property属性

希望您使用的是Windows窗体

答案 1 :(得分:1)

您可以计算要绘制的文本的宽度,如果它超过文本框宽度,则返回。

HERE你可以找到一个很好的例子。

答案 2 :(得分:1)

假设WinForms,试试这个:

private bool textExceedsWidth;

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    textExceedsWidth = false;

    if (e.KeyCode == Keys.Back)
        return;

    Size textSize = TextRenderer.MeasureText(textBox1.Text, textBox1.Font);

    if (textBox1.Width < textSize.Width)
        textExceedsWith = true;
}

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (textExceedsWidth)
        e.Handled = true;
}

答案 3 :(得分:0)

不,要做到这一点,你必须手动计算文本框宽度可以输入的最大字符数。恐怕。您还必须考虑字体和字体大小

答案 4 :(得分:0)

我知道这个问题有点陈旧,但任何人都认为这是乔治回答的扩展。它适用于Ctrl + v,上下文菜单粘贴和键盘输入。

private string oldText;

private void txtDescrip_KeyPress(object sender, KeyPressEventArgs e)
{
    oldText = txtDescrip.Text;
}

private void txtDescrip_TextChanged(object sender, EventArgs e)
{
    Size textSize = TextRenderer.MeasureText(txtDescrip.Text, txtDescrip.Font);

    if (textSize.Width > txtDescrip.Width)//better spacing txtDescrip.Width - 4
        txtDescrip.Text = oldText;
    else
        oldText = txtDescrip.Text;
}