0

I have a input and I want it to accept only the data type I want like string or double. Is there any way I can do it programmatically?

I tried

TextBox text = new TextBox();
text.Type = 'numberic'; // an input that only accepts int.
text.Type = 'double';//or like this.

My app is dynamic so I want it to s.th like this . More general for all data types. but it didn't work. I used to say type in html but here I don't know if there is way to do it or not in wpf?

Eboy
  • 61
  • 7

1 Answers1

1

you can add on textChanged event to the text box and then handle the data changed

follow this example:

TextBox textBox = new TextBox();
textBox.TextChanged += TextBox_TextChanged;

For int datatype:

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        TextBox textBox = sender as TextBox;
        int iValue = -1;

        if (Int32.TryParse(textBox.Text, out iValue) == false)
        {
            TextChange textChange = e.Changes.ElementAt<TextChange>(0);
            int iAddedLength = textChange.AddedLength;
            int iOffset = textChange.Offset;
            textBox.Text = textBox.Text.Remove(iOffset, iAddedLength);
            textBox.Select(textBox.Text.Length, textBox.Text.Length);
        }
    }

in the case you want another number datatype just change ivalue to float or double etc..

and then use float.tryparse or double.tryparse

I hope this can help.

  • Thankyou for your help but I had a question. Should I only change iValue data type or I should change all of the ints to double? – Eboy Sep 09 '22 at 15:04
  • 1
    Just the iValue and the parsing function try hold ctrl and click on the function to see the type of the reference value you should pass. the iAddedLength is always an integer value because will return the number of characters added to the text when the text changed the offset is the index where the changing is happening and we are using them from the text later by calling textbox.text.remove(startindex,length of characters added) – karam yakoub agha Sep 09 '22 at 15:22