0

我有个问题。我希望我的文本框不接受不存在的数字。我已经做了,所以我的文本框不接受十进制。但是当我输入例如 0865 时,我希望它立即转换为 865。我不知道该怎么做。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Globalization;

namespace KeepThemTogether
{
    public partial class MainPage : PhoneApplicationPage
    {
        int from_a, to_b, generatedNumber;

        public MainPage()
        {
            InitializeComponent();
        }

        private void from_text(object sender, TextChangedEventArgs e)
        {

        }

        private void to_change(object sender, TextChangedEventArgs e)
        {

        }

        private void ShowGen()
        {
            ShGenTxt.Text = Convert.ToString(generatedNumber);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            from_a = Int32.Parse(FromTxt.Text);
            to_b = Int32.Parse(ToTxt.Text);        
            Random generate = new Random();
            generatedNumber = generate.Next(from_a, to_b);
            ShowGen();
        }

        private void from_up(object sender, KeyEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            if (txt.Text.Contains('.'))
            {
                txt.Text = txt.Text.Replace(".", "");
                txt.SelectionStart = txt.Text.Length;
            }
        }

        private void to_up(object sender, KeyEventArgs e)
        {
            TextBox txt = (TextBox)sender;
            if (txt.Text.Contains('.'))
            {
                txt.Text = txt.Text.Replace(".", "");
                txt.SelectionStart = txt.Text.Length;
            }
        }
    }
}
4

2 回答 2

0

我会使用正则表达式并使用_TextChanged 方法针对输入运行它。

private void textBox1_TextChanged(object sender, EventArgs e)
 {
     if (System.Text.RegularExpressions.Regex.IsMatch("[^0-9]", textBox1.Text))
     {
         MessageBox.Show("Please enter only numbers.");
         textBox1.Text.Remove(textBox1.Text.Length - 1);
     }
 }
于 2013-06-06T20:09:59.507 回答
0

如果您只想删除前导零,您可以使用它来处理 TextChanged 事件

private void RemoveLeadingZeros(object sender, EventArgs e)
{
    TextBox txt = (TextBox)sender;
    txt.Text = txt.Text.TrimStart('0');
}
于 2013-06-06T20:31:04.640 回答