【问题标题】:How to insert input into an array from a text box in C#如何将输入从C#中的文本框插入到数组中
【发布时间】:2014-11-23 16:48:14
【问题描述】:

当用户单击提交按钮时,我想将用户输入插入到数组中。 这是我写的,但它似乎不起作用。该表单称为form1,它是它自己的类,文本框是textbox1。注意:我是编程新手。

//This is my array
private string[] texts = new string[10];

        public string[] Texts
        {
            get { return texts; }
            set { texts = value; }
        }

//I then attempt to insert the value of the field into the textbox
form1 enterDetails = new form1();
for(int counter = 0; counter<Texts.Length; counter++)
{
texts[counter]=enterDetails.textbox1.Text;
}

【问题讨论】:

  • 什么不起作用?发生了什么?
  • 您似乎粘贴了 2 或 3 个来自不同范围的代码,无法判断发生了什么
  • 这可能无法解决您的问题,但仍然:一个属性的 setter 设置的变量与 getter 检索到的变量不同,这是一种 HUGE 代码气味

标签: c# arrays textbox windows-forms-designer windowsformsintegration


【解决方案1】:

你在这里犯了一些愚蠢的错误:

  1. 在 Texts 属性的设置器中你应该说

    texts = value;
    

    而不是guestNames = value;

  2. 您不需要创建 form1 的新实例,因为您上面编写的所有代码都已在 form1 类中。如果没有,请尝试获取 form1 的相同实例。

  3. 没有必要,但您应该设置属性而不是字段。

    替换

    texts[counter] = .......
    

    Texts[counter] = ..........
    

因此,您的完整代码应如下所示:

    public form1() //Initialize your properties in constructor.
    {
        Texts = new string[10]
    }

    private string[] texts;

    public string[] Texts
    {
        get {return texts; }
        set { texts = value; }
    }

    for(int counter = 0; counter<Texts.Length; counter++)
    {
        Texts[counter]=this.textbox1.Text;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-26
    • 1970-01-01
    • 2015-02-20
    • 2017-09-14
    相关资源
    最近更新 更多