简体   繁体   English

如何在用逗号分隔的文本框中输入多个双打并存储在包含双打的数组中?

[英]How can I enter multiple doubles into a textbox separated by commas and store in an Array which holds doubles?

I am trying to enter multiple values into a textbox and when I press a button they will be stored in an array. 我试图在文本框中输入多个值,当我按下按钮时,它们将存储在数组中。 Like this: 1.1, 2.2, 3.3, 4.4, 5.5 Then press the button and they are stored in index 0, 1, 2, 3, 4 像这样:1.1、2.2、3.3、4.4、5.5然后按按钮,它们被存储在索引0、1、2、3、4中

I understand that the values are a string and need to be converted, I think I am close to the answer but I am not sure, here is what I have been trying: 我知道这些值是一个字符串,需要转换,我想我很接近答案,但是我不确定,这是我一直在尝试的方法:

 private void textBox1_TextChanged(object sender, EventArgs e)
    {
        //five values entered from textbox
        string values = textBox1.Text;
        string[] EmailArr = values.Split(',');
        double[] yArray = new double[5] = Array.ConvertAll(values.Split(','), Double.Parse);
    }

I know this is wrong, but is it along the right lines? 我知道这是错误的,但是是否正确? Any help is appreciated! 任何帮助表示赞赏! Thank you! 谢谢!

the linq way : LINQ方式:

var yArray = textBox1.Text
                     .Split(',')
                     .Select(m => Double.Parse(m.Trim()))
                     .ToArray();

By the way, don't use that with a TextChanged event, rather with a Validated, or a Clicked on your button. 顺便说一句,不要将其与TextChanged事件一起使用,而应与Validated或Clicked on your button一起使用。

Edit 编辑

Follow this steps : 请按照以下步骤操作:

Double click on "YourForm".cs (to have the "design"). 双击“ YourForm” .cs(具有“设计”)。

Select your TextBox. 选择您的文本框。

Right click, choose "Properties". 右键单击,选择“属性”。

See the "Event list". 请参阅“事件列表”。

Remove anything on line "TextChanged" 删除“ TextChanged”行上的所有内容

DoubleClick on line Validated (this will add text on this line) DoubleClick在线已验证 (这将在此行添加文本)

This should open the "code" part. 这应该打开“代码”部分。

Past my answer's code into the new method "private void textBox1_Validated(...)" 将我的答案代码粘贴到新方法“ private void textBox1_Validated(...)”中

Remove all the code present in your question. 删除问题中存在的所有代码。

or the older fashion way: 或更旧的方式:

    string values = textBox1.Text;
    string[] EmailArr = values.Split(',');
    double[] dlbArr = new double[EmailArr.Length];
    int index = 0;
    foreach (string item in EmailArr)
    {
        dlbArr[index] = Convert.ToDouble(item[index]);
        index++;
    }

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

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