当我从DataGridView
获取特定数据并希望将其放入TextBox
时,我希望TextBox
只接受11个字符,而不是更多。
我如何实现这一目标?
textBox3.MaxLength = 11;
textBox3.Text= dataGridView1.CurrentRow.Cells["Phone Number"].Value.ToString();
答案 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