简体   繁体   English

将文本框转换为整数,从数组中获取字符串

[英]Converting Textbox to Integer, Taking String from Array

I'm trying to convert the user input from a textbox to an integer (in c#), and then output a value from an array with the index of that integer. 我试图将用户输入从文本框转换为整数(在C#中),然后从具有该整数索引的数组中输出一个值。 Here's a small part of my code: 这是我的代码的一小部分:

 public Form1()
{
 InitializeComponent();
        string[] Cmaj = new string [7];
            Cmaj[1] = "C";
            Cmaj[2] = "D";
            Cmaj[3] = "E";
            Cmaj[4] = "F";
            Cmaj[5] = "G";
            Cmaj[6] = "A";
            Cmaj[7] = "B";


       int roman = int.Parse(textBox3.Text);
       textBox4.Text = Cmaj[roman];

}

But each time I run this, I get an error about "int roman = int.Parse(textBox3.Text);" 但是每次运行此命令时,都会出现关于“ int roman = int.Parse(textBox3.Text);”的错误。 (Listed below). (下面列出)。 I originally had Convert.ToInt32 instead of int.Parse, but I saw another question about this topic that said to use parse rather than convert. 我最初使用的是Convert.ToInt32而不是int.Parse,但是我看到了关于此主题的另一个问题,据说使用解析而不是转换。 This, however, didn't change much. 但是,这并没有太大变化。 What should I do? 我该怎么办?

Error: An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll 错误:mscorlib.dll中发生了'System.FormatException'类型的未处理异常

Additional information: Input string was not in a correct format. 附加信息:输入字符串的格式不正确。

Thanks. 谢谢。

You are in the constructor of your component. 您在组件的构造函数中。 So the text is probably empty and cause an exception. 因此,文本可能为空并导致异常。

Probably you want to add the parsing logic on an event like text changed or button clicked. 可能您想在诸如文本更改或按钮单击之类的事件上添加解析逻辑。

So from the form builder add the event handler, than move the logic into that method. 因此,从表单构建器添加事件处理程序,而不是将逻辑移到该方法中。

To better understand when each metdod il called I suggest you to add a break point on the first { of each method, and you can follow the event flow. 为了更好地理解每个方法调用的时间,建议您在每个方法的第一个{处添加一个断点,然后可以遵循事件流。

Is a good idea to manage error: you can wrap with a try...catch or use int.TryParse that requires an out variable. 管理错误是一个好主意:您可以使用try ... catch进行包装,也可以使用需要out变量的int.TryParse。

使用不同的方式

  1. Convert.ToInt32(string);
  2. int val = 0; Int32.TryParse(string, out val );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM