0

基本上,下面的第一个 for 语句会根据用户输入创建一个 testvalue 标签列表。

第二个 for 语句应该计算出创建的动态标签的总数,但是当我播放它时,我收到一条错误消息,说“输入字符串的格式不正确”。tots += double.Parse(value[p].ToString());任何帮助将不胜感激。 谢谢

ArrayList value = new ArrayList();

int p =0;

for (int i = 0; i < weight.Count; i++)
{
    Label test = new Label();
    System.Drawing.Point l8 = new System.Drawing.Point(440, 48 + s);
    test.Location = l8;
    value.Add(test);

    k += 35;

    Label l2 = testpercent1[i] as Label;
    Double.TryParse(l2.Text.Trim(), out label2);
    Label l = testpercent2[i] as Label;
    Double.TryParse(l.Text.Trim(), out label1);
    Double testvalue = Math.Round(((label1 * .3) + (label2 * .4)));
    test.Text = testvalue.ToString();
}

Double total = 0;
for (int p = 0; p < value.Count; p++)
{
    tots += double.Parse(value[p].ToString());
}
4

5 回答 5

3
tots += double.Parse(((Label)value[p]).Text);
于 2012-05-01T17:04:22.893 回答
1

value[p] is of type Label. If you want to get the text value of the label, you should use value[p].Text.

Double total = 0;
for (int p = 0; p < value.Count; p++)
{
   tots += double.Parse(((Label)value[p]).Text);
}

Another thing, you should use List<Label> for value instead of ArrayList.

于 2012-05-01T17:05:36.637 回答
1

You are trying to parse the ToString() of a label. Were you instead looking to parse some property of the label?

When you call value[p], whats being returned is a on object of type Label. If you wanted to parse the text of the label your code would instead be

tots += double.Parse(((Label)value[p]).Text);

于 2012-05-01T17:05:39.117 回答
1

It's obvious you are adding a control to the ArrayList. So this don't work:

tots += double.Parse(value[p].ToString());

I reccomend you to do:

value.Add(test.Text);

Then:

tots += double.Parse(value[p]);

PS: Please use a List<string> instead of an ArrayList.

于 2012-05-01T17:05:56.163 回答
1

Storing your data in labels is a very bad idea. Use a data structure that is better suited for this purpose like an array or a list of doubles. Only use the lables for displaying the data.

double[] values = new double[N];
Label[] lables = new Label[N]; // Only for display!

//  Calculate (just as an example)
double result = values[i] + values[k];

// NOT LIKE THIS!
double result = Double.Parse(labels[i]) + Double.Parse(labels[k]);
于 2012-05-01T17:08:03.727 回答