从C#中的动态NumericUpDown获取值

时间:2014-05-19 17:41:09

标签: c# winforms

我创建了动态NumericUpDown。我想保存用户输入的值。我怎样才能做到这一点。在我保存值后,我想用它们做一些时间操作。知道我不知道每次用户想要的NumericUpDown数量吗?

// To set up the location for the NumericUpDown
int xCoor;
int yCoor;

Random coor = new Random();

// Button to create the NumericUpDown

private void btnRun_Click(object sender, EventArgs e)
{

    /// I am assuming that the user choice is 8
    int value = 8;

    //this calls the method which is going to create NumericUpDown
    this.AddNewNumrical(value);

}

//Method to Create NumericUpDown
private void AddNewNumrical(int numiraclNew)
{

    for (int x = 0; x < numiraclNew; x++)
    {

        for (int y = 0; y < 1; y++)
        {

            NumericUpDown numiNumber = new NumericUpDown();
            xCoor = coor.Next(0, 700);
            yCoor = coor.Next(0, 710);
            numiNumber.Location = new Point(xCoor, yCoor);


            numiNumber.Size = new System.Drawing.Size(50, 15);
            numiNumber.Maximum = 1000;
            numiNumber.Minimum = 1;
            this.pnlNodes.Controls.Add(numiNumber);

        }
    }
}

1 个答案:

答案 0 :(得分:1)

只需将新的NumericUpDown控件存储在另一个列表中即可!您还可以在Controls集合中搜索NumericUpDown控件,但是您可能会选择一些您不想要的内容:

List<NumericUpDown> numberControls = new List<NumericUpDown>();

//Method to Create NumericUpDown
private void AddNewNumrical(int numiraclNew)
{

    for (int x = 0; x < numiraclNew; x++)
    {
        NumericUpDown numiNumber = new NumericUpDown();
        xCoor = coor.Next(0, 700);
        yCoor = coor.Next(0, 710);
        numiNumber.Location = new Point(xCoor, yCoor);

        numiNumber.Size = new System.Drawing.Size(50, 15);
        numiNumber.Maximum = 1000;
        numiNumber.Minimum = 1;
        numberControls.Add(numiNumber); //Save the control off for later
        this.pnlNodes.Controls.Add(numiNumber);
    }
}

然后您可以在以后使用它来做任何你想做的事情:

private void Foo()
{
    foreach (NumericUpDown userSelection in numberControls)
    {
         //Do whatever with userSelection.Value
    }
}