KrisPus
KrisPus

Reputation: 53

textbox only allow ip address in textbox c#

I'm trying to make a textbox only allow IP Addresses without validation using internet. I'm going to have a "private void textBox3_TextChanged" or a "timer1_Tick" which does the job. and each time I type or it ticks, it will check if it is a valid. That's why I want it to be fast, and only use a simple local code to check if it's valid, meaning 0.0.0.0 - 255.255.255.255.

First, it should not do anything, but when an ip has been written, it will start a timer which then checks if the ip is reachable or not. The goal of this, is that when the IP has been written, a picturebox will turn red if ip is not reachable after about 4 secounds, and if it's reachable, it will turn green, then stop till "textbox3_TextChanged"

I tried something like ping, but it crashed if nothing was typed and it lagged if ip was not reachable:

private void timer1_Tick(object sender, EventArgs e)
    {
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions();

        options.DontFragment = false;


        // Create a buffer of 32 bytes of data to be transmitted.
        string data = "ping";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 120;
        PingReply reply = pingSender.Send(textBox3.Text, timeout, buffer, options);
        if (reply.Status == IPStatus.Success)
        {
            pictureBox4.BackColor = Color.LimeGreen;
        }
        else
            pictureBox4.BackColor = Color.Red;
    }

Here is a screenshot: https://i.sstatic.net/yF7LK.jpg

Please help :)

Upvotes: 0

Views: 3758

Answers (3)

sadegh salehi
sadegh salehi

Reputation: 11

I was able to check the maskedtextbox values ​​with three functions. In fact, I set up 4 maskedtextbox for each IP so that the user thinks he is entering an IP in a textbox, and I used the following functions for each text box.

public void Fanction_mouse_click(MaskedTextBox txt_name)
{
    txt_name.SelectionStart = 0;
}

public void Fanction_KeyUp(MaskedTextBox txt_name, MaskedTextBox next_txtbox)
{
    if (txt_name.Text.Trim() != "")
    {
        if (Convert.ToInt32(txt_name.Text.Trim().ToString()) > 255)
        {
            txt_name.Text = txt_name.Text.Remove(txt_name.TextLength - 1, 1);
        }
        if (Convert.ToInt32(txt_name.Text.Trim().ToString()) < 256 && Convert.ToInt32(txt_name.Text.Trim().ToString()) > 99)
        {
            next_txtbox.Select();
        }
    }
    if (txt_name.Text.StartsWith("0")&& txt_name.Text.Length>1) {
        txt_name.Text = txt_name.Text.Remove(0, 1);
    }
}

public void Fanction_KeyPress(MaskedTextBox txt_name,string press, MaskedTextBox next_txtbox)
{
    if (press == "."&& txt_name.Text.Trim()!="")
    {
        next_txtbox.Select();
    }
}

picture of 4 maskedtextbox

Upvotes: 0

GSmyrlis
GSmyrlis

Reputation: 53

   private void TxtEthStaticIP_Leave(object sender, EventArgs e)
        {
            Regex regex = new Regex(@"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b");
            Match match = regex.Match(TxtEthStaticIP.Text);
            if (match.Success == false)
            {
                TxtEthStaticIP.Text = approvedethernetip;
            }
            else
            {
                approvedethernetip = TxtEthStaticIP.Text;
            }
        }

This is another idea of having a TextBox works like this. You have to declare an approved string for default text and this might help some situations who look like this.

An even better solution could be Validation and Validated events of the TextBox

Upvotes: 0

Quentin Roger
Quentin Roger

Reputation: 6538

You can try to replace textbox3_TextChanged by something like this :

(For this example my interface got one TextBox called textBox and one TextBlock called textBlock)

//async to not freeze the UI
private async void TextBox_OnTextChanged(object sender, TextChangedEventArgs e)
{
    Ping pingSender = new Ping();
    var tb = (TextBox)sender;

    //a little regex to check if the texbox contains a valid ip adress (ipv4 only).
    //This way you limit the number of useless calls to ping.
    Regex rgx = new Regex(@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");
    if (rgx.IsMatch(tb.Text))
    {
        int timeout = 120;
        try
        {
            var reply = await pingSender.SendPingAsync(tb.Text, timeout);
            textBlock.Text = reply.Status == IPStatus.Success ? "OK" : "KO";
        }          
        catch (Exception ex) when (ex is TimeoutException || ex is PingException)
        {
            textBlock.Text = "KO";
        }
    }
    else
    {
        if (textBlock != null)
        {
            textBlock.Text = "Not valid ip";
        }
    }
}

Upvotes: 1

Related Questions