我正在尝试以动态生成的形式获取用户在文本框中输入的值。另一种方法是加载和解析XML文件,并创建一个对象,该对象具有在文件中找到的设置(服务器,端口,标题等)的特定getter和setter。
使用像这样的标签和文本框创建动态表单。它的设计目的只是为了显示XML文件中的信息,我正在尝试实现一个允许用户在将信息再次保存到文件之前编辑信息的系统。我正在使用保存和编辑XML文件的方法,但我很遗憾如何将任何给定文本框中的输入与表示要更改的XML文件中的键的关联标签相关联。
下面是当前的表单实现,其中标签和文本框是作为foreach循环的一部分创建的。我尝试创建textbox.Leave eventHandler来跟踪用户何时完成更改值,但我无法弄清楚如何知道它与哪个标签相关联。
var sortedSettings = new SortedDictionary<string, string>(theSettings.Settings);
int numSettings = sortedSettings.Count;
TextBox[] txt = new TextBox[numSettings];
Label[] label = new Label[numSettings];
int labelSpacing = this.labelSecond.Top - this.labelTop.Bottom;
int textSpacing = this.textBoxSecond.Top - this.textBoxTop.Bottom;
int line = 0;
foreach (KeyValuePair<string, string> key in sortedSettings)
{
label[line] = new Label();
label[line].Text = key.Key;
label[line].Left = this.labelTop.Left;
label[line].Height = this.labelTop.Height;
label[line].Width = this.labelTop.Width;
txt[line] = new TextBox();
txt[line].Text = key.Value;
txt[line].Left = this.textBoxTop.Left;
txt[line].Height = this.textBoxTop.Height;
txt[line].Width = this.textBoxTop.Width;
txt[line].ReadOnly = false;
// Attach and initialize EventHandler for template textbox on Leave
txt[line].Leave += new System.EventHandler(txt_Leave);
if (line > 0)
{
label[line].Top = label[line - 1].Bottom + labelSpacing;
txt[line].Top = txt[line - 1].Bottom + textSpacing;
}
else
{
label[line].Top = this.labelTop.Top;
txt[line].Top = this.textBoxTop.Top;
}
this.Controls.Add(label[line]);
this.Controls.Add(txt[line]);
line++;
}
private void txt_Leave(object sender, EventArgs e)
{
String enteredVal = sender;
FormUtilities.FindAndCenterMsgBox(this.Bounds, true, "EventChecker");
MessageBox.Show("The current value of LABEL is " + enteredVal, "EventChecker");
}
答案 0 :(得分:1)
示例(在foreach循环中):
txt[line] = new TextBox();
txt[line].Text = key.Value;
txt[line].Tag = label[line];
获取与TextBox关联的标签:
TextBox t = txt[0];
Label l = t.Tag as Label;
//Here is how you identify textbox which generated the event.
private void txt_Leave(object sender, EventArgs e)
{
TextBox tb = sender as TextBox;
//..
}