【问题标题】:How to convert a string value into "int" in c#.net如何在 c#.net 中将字符串值转换为“int”
【发布时间】:2016-01-14 17:53:19
【问题描述】:
protected void Button1_Click(object sender, EventArgs e)
{
    string b = "hello";
    TextBox1.Text = Convert.ToInt32(b).ToString();
}

错误:

Input string was not in a correct format .如何转换 在 C# 中将字符串转换为整数?

【问题讨论】:

  • 你好应该是数字吗?
  • 你读过关于Convert类的文档吗?
  • 你已经看过下面的帖子了吗? stackoverflow.com/questions/1019793/…
  • 您将string 转换为int 并再次从int 转换为string 这没有意义。

标签: c# type-conversion


【解决方案1】:
 string b = "hello";
 Int32 outPut=0;
 Int32.TryParse(b,out outPut);//0
 TextBox1.Text = outPut.ToString();

由于 b 包含一个无法转换为整数的字符串,您将在 TextBox1 中获得 0

Int32.Parse()Convert.Int32() 是将字符串转换为整数的其他可能方法。但是这两种方法都不能处理null,它们只有在方法的输入可转换为整数时才会转换,否则会抛出格式异常

Int32.TryParse() 不会在错误时抛出任何异常 输入,它在输入错误的情况下给出0。并返回Boolean 表示转换是否成功的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-15
    • 2011-07-11
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多