[英]How do I restrict the number of character of data before inserting it to the a table?
I want to restrict the number of character before inserting it to the table. 我想在将字符插入表格之前限制字符数。 For example, I retrieved the value of the column "Address" whose data length is of 44 characters.
例如,我检索了数据长度为44个字符的“Address”列的值。 But when I need to insert this value to another table, I want to restrict only 40 characters in the column "Address2" of another table as its data type is of 40 in length.
但是当我需要将此值插入另一个表时,我想在另一个表的“Address2”列中仅限制40个字符,因为其数据类型的长度为40。 Please help
请帮忙
Try this: 尝试这个:
If (sAddress != null && sAddress.Length > 40) {
sAddress = sAddress.SubString(0, 40)
}
Put some validation on text box which is present on your form/page to accept only 40 characters . 对表单/页面上的文本框进行一些验证,只接受40个字符。 You can use following regular expression which will validate the input text for max 40 characters -
您可以使用以下正则表达式来验证最多40个字符的输入文本 -
^.{1,40}$
You can check the strings length simply and make some action if it is greater that the allowed length. 您可以简单地检查字符串长度,如果它大于允许的长度,则执行一些操作。
For example, You can truncate the string with a function like this: 例如,您可以使用如下函数截断字符串:
string truncate(string s, int length)
{
return ( s.Length > length ) ? s.Substring(0, length) : s;
}
so truncate(Address,40)
will give You a shorter string and You can use it every time with this short form with any length. 所以
truncate(Address,40)
会给你一个更短的字符串,你可以每次使用这个短格式任意长度。
string YourVar = YourTextBox.text;
string VarToInsert = YourVar.Substring(0,40);
For MVVM in WPF you can use DataAnnotations 对于WPF中的MVVM,您可以使用DataAnnotations
[Range(1,40)]
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged("Name"));
}
}
XAML XAML
<TextBox Text="{Binding Name, ValidatesOnDataErrors=True}">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.