【问题标题】:Saving User Input in a Dynamically Created Form将用户输入保存在动态创建的表单中
【发布时间】:2014-08-11 14:21:30
【问题描述】:

我正在尝试以动态生成的形式获取用户在文本框中输入的值。另一种方法加载并解析 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");
}

【问题讨论】:

    标签: c# xml forms dynamic textbox


    【解决方案1】:

    一种选择是使用TextBox.Tag 属性。

    示例(在 foreach 循环中):

    txt[line] = new TextBox();
    txt[line].Text = key.Value;
    txt[line].Tag = label[line];
    

    获取与文本框关联的标签:

    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;
        //..
    }
    

    【讨论】:

    • 非常感谢! tag 属性非常有用!但是有没有办法在 EventHandler 中识别哪个文本框触发了它?
    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 2017-05-21
    • 2020-10-30
    • 2018-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多