Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c# - How to get value of programmatically created NumericUpDown?

I have program which creates multiple NumericUpDowns depending on user input (1-5). I know how to get total value but how can I get value of each individual NumericUpDown. I was trying to test this using label1 but I get NullReferenceException error.

   NumericUpDown test= new NumericUpDown();
    test.Name = "mynum" + Convert.ToString(count2);
    numericUpDown.Add(test);
    System.Drawing.Point i = new System.Drawing.Point(8, 20+ i * 25);
    test.Location = i;
    test.Size = new System.Drawing.Size(50, 20);
    this.Controls.Add(test);
    test.ValueChanged += new EventHandler(mytotal);

NullReferenceException error is thrown at this line.

label1.Text = test.Controls["mynum0"].Text;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
 test.Name = "mynum" + Convert.ToString(count2);

You named it "mynum" plus a number. So you can't find it back with test.Controls["test0"]. Fix the indexer argument to "mynum0" or the Name property assignment.

The next problem you have is that the NumericUpDown control doesn't have a functional Text property. It uses Value instead, a number instead of a string. So you'll need to cast the control to NumericUpDown to access the Value property.

 var nud = this.Controls["mynum0"] as NumericUpDown;
 if (nud == null) throw new Exception("I can't do that Dave, it isn't there");
 label1.Text = nud.Value.ToString();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...