Pankaj Sejwal
Pankaj Sejwal

Reputation: 1595

Specifying data type on windows form textfield

I am a beginner in Visual Studio ( 2010 ) and I want to accept some data from form to backend as say Integer or any other class's object instead of getting in the headache of manually making the conversion(which I will have to learn if its not possible).

Textbox1.Text always returns String while I want it as Textbox1.ClassName to kind of get automatic conversion.

is it possible ?

Upvotes: 1

Views: 740

Answers (2)

Sinatr
Sinatr

Reputation: 22008

In winforms common practice is to enhance controls by making own, here is something I've used (cut version):

[System.ComponentModel.DesignerCategory("Code")]
public class MyTextBox : TextBox
{
    [Browsable(false)]
    public int AsInt
    {
        get
        {
            int result;
            int.TryParse(Text, out result);
            return result;
        }
    }
    [Browsable(false)]
    public bool IsIntOk
    {
        get
        {
            int result;
            return int.TryParse(Text, out result);
        }
    }

    protected override void OnTextChanged(EventArgs e)
    {
        ForeColor = IsIntOk ? SystemColors.WindowText : Color.Red;
        base.OnTextChanged(e);
    }
}

Upvotes: 1

Franck
Franck

Reputation: 4440

You will need to use conversion, you have no choice. What you can do is extention on the textbox and write your converter in it. Most likely passing a default value in case the conversion fails

Something like :

public static class Extensions
{
    public static int TextAsInt(this TextBox txt, int defaultValue)
    {
        var result = 0;

        if (!Int32.TryParse(txt.Text, out result))
        {
            result = defaultValue;
        }

        return result;
    }
}

and then you can use it like so :

int result = Textbox1.TextAsInt(50);

if the conversion fail the value returned would be 50

Now that said, the most intelligent way to make an extension like this reusable is to extend the string object and not the textbox. So it would be called on the Textbox1.Text.TextAsInt(50); instead.

Upvotes: 2

Related Questions