how to restrict the length of entries in text box

2019-06-09 17:41发布

c#: By default text box accepts n number of entries,

I want to restrict the entries to its width

Is there any property in text box through which i can achive this,

标签: c# textbox
5条回答
2楼-- · 2019-06-09 18:27

Assuming WinForms, try this:

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;
}
查看更多
We Are One
3楼-- · 2019-06-09 18:29

You could compute the width of the text to be drawn and if it exceeds the textbox width then return.

HERE you can find a great example.

查看更多
Fickle 薄情
4楼-- · 2019-06-09 18:30

default it accepts only 32767 of chars.

You can set the MaxLength property of the textbox in the textbox property

Hope you are using windows forms

查看更多
仙女界的扛把子
5楼-- · 2019-06-09 18:41

No, to do this you will have to calculate the maximium number of characters they can enter by the text box width manually I'm afraid. You'll also have to take into consideration the font and font size too

查看更多
Ridiculous、
6楼-- · 2019-06-09 18:41

I know this question is a bit old but to any one looking this is an expansion of George answer. It works with Ctrl + v, context menu paste and typing from key board.

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;
}
查看更多
登录 后发表回答