如何从动态创建的NumericUpDown中获取值?

本文关键字:获取 NumericUpDown 动态 创建 | 更新日期: 2023-09-27 18:08:36

如何在c#中获得动态NumericUpDown的值?

这是我的代码,

for (int i=0; i<n;i++)
{
    NumericUpDown notele = new NumericUpDown();
    notele.Name = "note" + i.ToString();              
    notele.Location = new System.Drawing.Point(280, 208 + (30 * i));
    notele.Size = new System.Drawing.Size(40, 25);
    notele.BackColor = System.Drawing.SystemColors.ControlDark;
    notele.Maximum = new decimal(new int[] {10,0,0, 0});
    this.Controls.Add(notele);
}

如何从动态创建的NumericUpDown中获取值?

使用窗体的Control集合访问控件,并将numericUpDown控件的名称传递给它:

var numericUpDown  = this.Controls["note0"] as NumericUpDown;
if(numericUpDown != null)
{
   var value = numericUpDown.Value;
}

您仍然可以使用ValueChanged事件:

...
    notelle.ValueChanged += UpDnValueChangedHandler;
    this.Controls.Add(notele);
}
private void UpDnValueChangedHandler(object sender, EventArgs e)
{
    // sender references the control which value was changed:
    NumericUpDown notelle = sender as NumericUpDown;
    // further processing goes here
}