日期:2014-05-17  浏览次数:20819 次

textbox 输入一个数字自动加逗号(CS)
textbox 输入一个数字自动加逗号,且只能输入数字,每输入一位自动价格逗号,如:1,2,3,...

求大侠指导!

------解决方案--------------------
private void IDtextBox_KeyPress(object sender, KeyPressEventArgs e)
{
int ch = e.KeyChar;
if (((ch >= 48) && (ch <= 57) || ch == 8 || ch == 13) == false)
{
e.Handled = true;

}
}
------解决方案--------------------
HTML code
<head runat="server">
    <title>无标题页</title>
    <script type="text/javascript">
        function input(obj){
            var reg=/^(\d,?)*$/;
            if(reg.test(obj.value))
                obj.value+=",";
            else
                obj.value=obj.value.replace(/(\d,)[^\d]/g,"$1");
        }
    </script>
</head>
<body>
    <input id="Text1" type="text" onkeyup="input(this)" />    
</body>
</html>

------解决方案--------------------
private void textBox1_TextChanged(object sender, EventArgs e)
{
string text = this.textBox1.Text;
Regex reg = new Regex(@"[0-9]{1}[,]?");

MatchCollection match = reg.Matches(text);

text = string.Empty;

foreach (Match m in match)
text += m.Value.TrimEnd(',') + ',';

this.textBox1.Text = text.TrimEnd(',');
}


------解决方案--------------------
VB.NET code

Private Sub TextBox1_KeyPress1(ByVal sender As Object, ByValeAsSystem.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
        If Asc(e.KeyChar) <> Keys.Back Then
            If e.KeyChar < "0" Or e.KeyChar > "9" Then
                MessageBox.Show("只能输入整数!")
                e.Handled = True
                Exit Sub
            Else
                TextBox1.Text = TextBox1.Text.Trim() + ","
            End If
        End If
    End Sub

------解决方案--------------------
简单写了一下,要想完美处理,还得处理更多的东西,鼠标啦,剪切操作啦,拖放等等
C# code
       private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            TextBox t = sender as TextBox;
            if (e.KeyChar >= '0' && e.KeyChar <= '9')
            {
                t.SelectedText = string.Concat(e.KeyChar , ',');
                    e.Handled = true;
            }
            else if (e.KeyChar == (char)ConsoleKey.Backspace)
            {
                if (t.SelectionStart >= 2)
                {
                    t.SelectionStart -= 2;
                    t.SelectionLength = 2;
                    t.SelectedText = "";
                }
                e.Handled = true;
            }
            else
                e.Handled = true;
        }