Skip to main content
 首页 » 编程设计

c#之如何在文本字段中显示 int 值

2024年02月06日14EasonJim

我正在 Visual Studio 中开发一个 Web 表单应用程序,并且我正在尝试构建一个更新网格。

我可以从记录中引入 string 值,但是在引入 int 值时遇到了麻烦,例如 Age.

我已经在下面发布了我的代码。

代码:

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(); 
}  

我想我需要将 int 转换为 string,但我不确定该怎么做?

请您参考如下方法:

保存时转成int,设置值时转回string,

 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(); 
    }  

和

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