WPF - 只需要使用特定字符串更改文本框的字符

时间:2017-02-24 14:16:29

标签: c# wpf textbox

我正在尝试创建一个工具来支持我的网络上的用户,基本上我有一个你输入主机名的文本框。我想知道是否只有在框中输入一个6位数的字符时才能在文本框中附加字符。如果是其他任何事情,请不要管它。

基本上如果数字是123456,那么在“C123456”开头加上“C” 但如果有人已经把C放进去 - 什么都不做。

还有其他字符(对于其他主机名)我不想改变。只有输入6位数字才能将“c”放在前面。

示例代码:

这是我到目前为止所做的:

        private void IPfind(object sender, KeyEventArgs e)
        {

            if (e.Key == Key.Enter)
            {
                TextBox tb = (TextBox)sender;
                string text = tb.Text.ToUpper();
                int num;
                if (int.TryParse(text, out num))
                {
                    // it is an integer. Simply add a C at the begining if it has enough characters

                    if (text.Length == 6)
                    {
                        tb.Text = 'C' + text;
                        tb.CaretIndex = tb.Text.Length;
                    }
                    else
                    {

                    }
                    Ipbox.Clear();
                    try
                    {
                        // Host Name resolution to IP
                        IPHostEntry host = Dns.GetHostEntry(Assetbox.Text.Trim());
                        IPAddress[] ipaddr = host.AddressList;
                        // Loop through the IP Address array and add the IP address
                        foreach (IPAddress addr in ipaddr)
                        {
                            // Finds the IP V4 address
                            if (addr.AddressFamily == AddressFamily.InterNetwork)
                                Ipbox.Text = (addr.ToString());
                        }
                    }

3 个答案:

答案 0 :(得分:0)

所以我认为Regex在这里非常有用,

使你的文本框然后在XAMl中创建一个textchanged事件,

 <TextBox x:Name="textBox" TextChanged="textBox_TextChanged"/>

然后在C#(代码隐藏)中,您可以将代码添加到事件中,

 private void textBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        var pattern = new Regex(@"(\w[0-9]{6})"); //This is a regex pattern, you can make it much more intelligent, like if you just want P or C chars to accepted rather than any letter
        var isThereMatch = pattern.Match(textBox.Text); // Is there a match?
        string strThingIwannaSAVE = isThereMatch.ToString(); //If there is save that string so you can manipulate it
        if (textBox.Text.Length > 6) //only execute the following code if you have enough characted in your box
        { 
        if (string.IsNullOrWhiteSpace(strThingIwannaSAVE)) //if there is no match or its just whitespaces for some reason, empty out your box or display a message or whatever else
        {
            MessageBox.Show("Wrong input");
                textBox.Text = String.Empty;
        }
        else 
        {  
          //String is good, add it to a database? do something to it?
        }           
      }
    }

<强> 修改

如果您只想匹配P或C字符加数字,请制作两个正则表达式模式,

var pattern = new Regex(@"(c{1}[0-9]{6})");
var pattern2 = new Regex(@"(p{1}[0-9]{6})");

然后检查文本框中的匹配项

答案 1 :(得分:0)

使用if块来检查所有内容。我在评论中解释了不同的部分:

    bool _changing = false; // since you are going to change Text you need this to stop a loop or other errors
    private void Tb_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (_changing)
            return;
        _changing = true;
        TextBox tb = (TextBox)sender;
        string text = tb.Text.ToUpper();

        if (text == null || text.Length == 0)
        {
            // The user has not enter enough characters yet
            return;
        } 

        int num;
        if (int.TryParse(text, out num))
        {
            // it is an integer. Simply add a C at the begining if it has enough characters
            if (text.Length == 6)
            {
                tb.Text = 'C' + text;
                tb.CaretIndex = tb.Text.Length;
            }
            else
            {
                // let use to continue typing
            }
        }
        else
        {
            // it is not an integer
            //check if it starts with P or C
            if (text[0] == 'C' || text[0] == 'P')
            {
                string textrest = text.Remove(0, 1);
                if (textrest.Length == 0)
                {
                    // it is just a C or P
                    return;
                }

                if (int.TryParse(textrest, out num))
                {
                    // it became an integer after removing the first char. It is OK then.
                }
                else
                {
                    // it is not a number and removing the first C or P did not solve the problem
                    // throw new FormatException();
                    // or
                    MessageBox.Show("Wrong Format. Enter ###### or C###### or P#######");
                }
            }
            else
            {
                // it is not a number and the reason is not because it starts with C or P
                // throw new FormatException();
                // or
                MessageBox.Show("Wrong Format. Enter ###### or C###### or P#######");
            }
        }
        _changing = false;
    }

答案 2 :(得分:0)

非常感谢@JohnChris和@Ramin

我使用了两种解决方案来解决这个问题

        TextBox tb = (TextBox)sender;
        string text = tb.Text;
        if (Regex.IsMatch(text, @"^\d+$") && text.Length == 6)
            {
                tb.Text = 'C' + text;
                tb.CaretIndex = tb.Text.Length;
            }