【问题标题】:Dynamic text boxes and using them动态文本框和使用它们
【发布时间】:2018-01-13 18:51:29
【问题描述】:

我已经生成了一些文本框,我希望用户在将数据添加到表单后在其中输入数据,然后我使用其中的数据进行一些计算。 我如何使用数据?

TextBox t3 = new TextBox();

t3.Top = 222 + ((addalternativebutton - 3) * 60);
t3.Left = 214;
t3.Width = 76;
t3.Height = 22;
t3.Name = "txtwaste" + addalternativebutton.ToString();

this.tabore.Controls.Add(t3);
ww[addalternativebutton] = Convert.ToDouble(t3.Text);

【问题讨论】:

  • 实现这一目标的方法不止一种。你能分享一些关于用例的更多细节吗?你是如何创建新的文本框的?在按钮单击?动态文本框的数量是否有限制?只有一个文本框参与一个计算还是有多个?最简单的方法是在 Dictionary 中维护文本框,其中文本框名称是键,文本框对象是值。并根据名称从字典中检索文本框并用于计算。
  • 按钮点击时创建的新文本框,每次点击都会创建一个新的文本框。然后用户在所有文本框中输入数据并按下计算按钮,我想使用所有文本框数据进行计算,例如我想对所有文本框数据求和。

标签: c# dynamic textbox


【解决方案1】:

正如我在 cmets 中提到的,您需要保留动态创建的文本框实例。如果需要处理分配给它们的名称,您可以使用通用字典,也可以使用通用列表。 以下解决方案我为您提供使用通用列表的解决方案。

首先需要一个保存文本框的列表。

public partial class Form1 : Form
{
    private List<TextBox> textBoxes;
    private int textBoxCount; //This is used to provide unique names to the 
                              //textboxes and to track the number of dynamic textboxes.

    public Form2()
    {
        InitializeComponent();
    }
}

现在在按钮的单击事件中,文本框被创建、定位并添加到列表以及 Form.Controls 中。

private void button1_Click(object sender, EventArgs e)
{
    textBoxCount += 1;
    TextBox t3 = new TextBox();
    t3.Top = 20 + (22 * textBoxCount); //You can put your own logic to set the Top of textbox.
    t3.Left = 120;
    t3.Width = 50;
    t3.Height = 20;
    t3.Name = "txtwaste" + textBoxCount; //You can use your own logic of creating new name.
    this.Controls.Add(t3);
    this.textBoxes.Add(t3);
}

现在,当您要计算单击另一个按钮时所有文本框的值的总和时。

private void button2_Click(object sender, EventArgs e)
{
    double totalValue = 0;
    foreach (var textBox in textBoxes)
    {
        double currentValue;
        if (double.TryParse(textBox.Text, out currentValue))
        {
            totalValue += currentValue;
        }
    }
    // Displaying totalValue in a label.
    lblTotalValue.Text = "Total Value : " + totalValue;
}

这应该可以帮助您解决问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多