如何限制文本框输入字符数?

时间:2016-11-02 16:26:47

标签: c# winforms textbox

当我从DataGridView获取特定数据并希望将其放入TextBox时,我希望TextBox只接受11个字符,而不是更多。

我如何实现这一目标?

textBox3.MaxLength = 11;
textBox3.Text= dataGridView1.CurrentRow.Cells["Phone Number"].Value.ToString();

1 个答案:

答案 0 :(得分:1)

使用SubString截断字符串。

// Set the MaxLength, may not be needed if the field cannot be altered manually
textBox3.MaxLength = 11;

// Get the text value
var text = dataGridView1.CurrentRow.Cells["Phone Number"].Value.ToString();

// Starting from the first character, take up to 11 characters max
textBox3.Text = text.Substring(0, text.Length > 11 ? 11 : text.Length);

示例:

string longString = "abcdefghijklmnop";
string shortString = "abcde";

结果:

  

longString 会显示 abcdefghijk
   shortString 会显示 abcde