【发布时间】:2016-08-26 12:55:28
【问题描述】:
我有一个代码,其中 TextBox 和 NumericUpDown 工具是通过 foreach 循环动态生成的。现在,我希望能够获得这两个值,其中每次迭代时,它们的值都将添加到数据库中的同一行。我有获取 NumericUpDown 值的代码,我想知道如何实现获取 TextBox 值。
生成动态 NumericUpDown 和 TextBox 的代码
t = temp.Split(';'); // e.g. t = Arial;32
int pointX = 70;
int pointY = 80;
int pointA = 300;
int pointB = 80;
for (int i = 0; i < N; i++)
{
foreach (object o in t)
{
TextBox a = new TextBox();
a.Text = o.ToString();
a.Location = new Point(pointX, pointY);
a.Size = new System.Drawing.Size(150, 25);
panel.Controls.Add(a);
panel.Show();
pointY += 30;
NumericUpDown note = new NumericUpDown();
note.Name = "Note" + i.ToString();
note.Location = new Point(pointA, pointB);
note.Size = new System.Drawing.Size(40, 25);
note.Maximum = new decimal(new int[] { 10, 0, 0, 0 });
panel.Controls.Add(note);
pointB += 30;
}
}
在按钮单击时获取动态 NumericUpDown 值的代码(数据库代码有效)
foreach (NumericUpDown ctlNumeric in panel.Controls.OfType<NumericUpDown>())
{
var value = ctlNumeric.Value;
int number = Decimal.ToInt32(value);
sample_save = "INSERT INTO forthesis (testVal) VALUES ('" + number + "');";
MySqlConnection myConn = new MySqlConnection(connectionString);
MySqlCommand myCommand = new MySqlCommand(sample_save, myConn);
MySqlDataAdapter da = new MySqlDataAdapter(myCommand);
MySqlDataReader myReader;
myConn.Open();
myReader = myCommand.ExecuteReader();
myConn.Close();
MessageBox.Show(number.ToString());
}
我怎样才能获得 TextBox(es) 中的值?您的帮助将不胜感激。非常感谢!!!
【问题讨论】:
-
您想将变量
number中的两个值都添加到数据库中吗? -
@Rakitić hmmm 我希望它存储在不同的变量中..
-
尝试使用字典之类的东西:stackoverflow.com/questions/12238599/find-wpf-control-by-name - 您可以为每个控件使用具有相同键的两个字典
-
@PaulF 我很难理解,但我会尝试。
-
我添加了一个答案以提供一种可能的解决方案。
标签: c# .net textbox iteration numericupdown