user4274473
user4274473

Reputation:

How to display int values in a textfield?

I am developing a web forms app in Visual Studio, and I am trying to build an update grid.

I can bring in the string values from a record but am having trouble when it comes to bring in the int values as in this case of Age.

I have posted my code below.

Code:

private void DisplayPersonData(Author p)
{
    txtFName.Text = p.Name;
    txtAge.Text = p.Age;//Problem is here 
}

protected void btnSearchId_Click(object sender, EventArgs e)
{
    int id = System.Convert.ToInt32(txtId.Text);
    hfId.Value = id.ToString();
    targetPerson = GetPersonById(id);
    DisplayPersonData(targetPerson);
}

protected void btnUpdate_Click(object sender, EventArgs e)
{
    targetPerson = GetPersonById(Convert.ToInt32(hfId.Value));
    targetPerson.Name = txtFName.Text;
    targetPerson.Age = txtAge.Text;//Problem is here 

    context.SaveChanges();
} 

I am thinking I need to convert the int to a string, but I am not sure how to do that ?

Upvotes: 0

Views: 566

Answers (3)

Benison Sam
Benison Sam

Reputation: 2825

You can use the ToString() method to convert the age integer value to string as shown below:

txtAge.Text = p.Age.ToString();

Or you can eve do the following:

txtAge.Text = Convert.ToString(p.Age);

Moreover, if you need to further use it for calculations then you will have to convert it back to Integer and that you can do by following:

Int32 Age = Convert.ToInt32(txtAge.Text);

For further details, you can go visit here or here

Upvotes: 1

Vandervidi
Vandervidi

Reputation: 295

You can use one of the following:

txtAge.Text = Convert.ToString(p.Age);
targetPerson.Age = Convert.ToString(txtAge.Text);

or

txtAge.Text = "" + p.Age;
targetPerson.Age = ""+ txtAge.Text;

or

txtAge.Text = p.Age.ToString();
targetPerson.Age = txtAge.Text.ToString();

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222722

Just convert to int when you save and convert back to string when you set the value,

 protected void btnUpdate_Click(object sender, EventArgs e)
    {
        targetPerson = GetPersonById(Convert.ToInt32(hfId.Value));
        targetPerson.Name = txtFName.Text;
        targetPerson.Age =  Convert.ToInt32(txtAge.Text);
        context.SaveChanges();
    } 

and

private void DisplayPersonData(Author p)
    {
        txtFName.Text = p.Name;
        txtAge.Text = p.Age.ToString(); 
    }

Upvotes: 2

Related Questions