问题
Here is the code in C# to allow only one decimal point in a textbox:
if textbox5.text.contains(".") && e.keychar="."
{
e.handled=true
}
I have to use it in VB.NET 2003 version, but I can't use the contains property. How can I do this?
回答1:
How about using the Text.IndexOf(".")
method instead? If it returns >=0 then you already have a decimal point.
If (textbox5.Text.IndexOf(".") >= 0 And e.KeyChar = ".") Then e.Handled = True
回答2:
Don't forget about the user's locale and number formats. I believe using a period ('.') as a decimal character is in the minority, world-wide. You can use CurrentUICulture
's NumberFormat
field to help you parse in the most correct way. Try using:
decimal d;
bool isValidInput = decimal.TryParse(
textBox1.Text,
System.Globalization.NumberStyles.AllowDecimalPoint,
System.Globalization.CultureInfo.CurrentUICulture.NumberFormat,
out d);
This will validate whether a number was entered properly. Using other NumberStyles
flags, you can control what kinds of numbers you want to allow, for example things like thousands separators.
*Sorry for C# here. VB.NET should be easy to adapt from this though; maybe some kind soul can edit it in.
回答3:
package Utility
{
import flash.events.Event;
import flashx.textLayout.operations.PasteOperation;
import spark.components.TextInput;
import spark.events.TextOperationEvent;
/**
* This is a text input component that can only input numbers.
* A number means a real number.
* @author Cheng Liang
* @version 0.0.1
*/
public class NumberInput extends TextInput
{
[Bindable("numberChange")]
/**
* Sets number as input value.
*/
public function set number(value : Number) : void
{
var s : String = value.toString();
if(text != s) {
text = s;
dispatchEvent(new Event("numberChange"));
}
}
public function get number() : Number
{
return Number(text);
}
public function NumberInput()
{
super();
this.addEventListener(TextOperationEvent.CHANGE, onTextChange);
}
protected function onTextChange(event : TextOperationEvent) : void
{
if (event.operation is PasteOperation)
{
TextInput(event.currentTarget).text='';
}
if(text == "" || text.length == 1) {
return;
}
/* To allow single (.) */
var idx : int = text.indexOf(".", 0);
if(idx >= 0) {
text = text.substring(0, idx + 1) + text.substring(idx + 1).replace(".", "");
}
/* To allow single (-) only at the 1st position*/
if(text.lastIndexOf("-")==0)
text ='-'+ text.substring(1);
else if(text.lastIndexOf("-")>0)
{
if(text.charAt(0)=='-')
text ='-'+ text.substring(1).replace("-", "");
else
text =text.replace("-", "");
}
var arr:Array = TextInput(event.currentTarget).text.split(".");
try{
if(arr[1] && String(arr[1]).length > 2){
TextInput(event.currentTarget).text = arr[0]+"."+String(arr[1]).slice(0,2);
}
}catch(err:Error){}
this.selectRange((text.length), (text.length));
}
}
}
来源:https://stackoverflow.com/questions/613963/how-can-i-allow-only-one-decimal-point-in-a-textbox