我有一个代码,其中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中的值呢?非常感谢您的帮助。非常感谢你!!!
答案 0 :(得分:0)
也许您可以使用字符串 - TextBox字典来保存匹配的配对文本框,如下所示:
Dictionary<string, TextBox> textboxes = new Dictionary<string, TextBox>();
for (int i = 0; i < N; i++)
{
foreach (object o in t)
{
TextBox a = new TextBox();
.....
NumericUpDown note = new NumericUpDown();
note.Name = "Note" + i.ToString();
......
textboxes.Add(note.Name, a);
}
}
foreach (NumericUpDown ctlNumeric in panel.Controls.OfType<NumericUpDown>())
{
var value = ctlNumeric.Value;
int number = Decimal.ToInt32(value);
TextBox tb = textboxes[ctrlNumeric.Name];
String text = tb.Text;
.........
}
如果要删除TextBoxs&amp; NumericUpDowns - 那么你也需要清除字典 - 否则它将保留对它们的引用&amp;它们不会被垃圾收集器清理。