2017-09-25 123 views
0

如何从文本框中获取字符串值并将其存储在数组字符串中?点击摘要按钮后,它将数组显示为列表框中的列表。将文本框值存储在一个字符串数组中,并在列表框中显示数组

例如,用户在文本框中输入“Tom”。点击进入! Tom存储在数组中 用户在文本框中输入“Nick”并点击Enter! Nick被存储在阵列中等等。

最后,当用户点击摘要按钮,列表框显示是这样的:

汤姆

尼克

有人可以帮助我?非常感谢你!

这是到目前为止我的代码

//Button helps to display the total number of customers 
     private void viewCustomerSBtn_Click(object sender, EventArgs e) 
     { 
      //Displays the string of names that are stored in cNames 
      //Creates an array to hold Customer Names 
      string[] cNames = new string[100]; 
      for (int i = 0; i < cNames.Length; i++) 
      { 
        cNames[i] = nameTextBox.Text; 
        reportListBox.Items.Add(cNames[i]); 
     } 

回答

1

你没有指定你在写什么样的应用程序:的WinForms,WPF等

您还没有表现出你的编码工作。

没有提供你在这里有完整的代码是一个建议,要寻找什么:

通常一个文本框具有Text属性,你也可以订阅该文本框,当用户点击Enter赶上合适的事件。您可以通过文本框的Text属性读取输入的名称,并将其添加到列表中,例如List<string>然后通过将Text属性设置为空字符串来清除文本框。

当用户点击摘要按钮时,您可以使用其Add()方法通过其Items属性将列表中的元素添加到列表框中。

这是我要去的方向。你可以谷歌其余。

更新#1

这里是一个工作示例:

using System; 
using System.Collections.Generic; 
using System.Data; 
using System.Linq; 
using System.Windows.Forms; 

namespace CollectNames 
{ 
    public partial class MainForm : Form 
    { 
     private static readonly List<string> names = new List<string>(); 

     public MainForm() 
     { 
      InitializeComponent(); 

      // Usually we set these event handlers using the 'Properties' tab for each specified control. 
      // => Click on the control once then press F4 so that 'Properties' tab will appear. 
      // Then these event subscriptions will be generated into MainForm.Designer.cs file. 
      // They are here just for clarity. 
      txtName.KeyUp += new System.Windows.Forms.KeyEventHandler(txtName_KeyUp); 
      btnSummary.Click += new System.EventHandler(btnSummary_Click); 
     } 

     private void txtName_KeyUp(object sender, KeyEventArgs e) 
     { 
      if (e.KeyCode == Keys.Enter) 
      { 
       names.Add(txtName.Text); 
       txtName.Text = String.Empty; 

       e.Handled = true; 
      } 
     } 

     private void btnSummary_Click(object sender, EventArgs e) 
     { 
      lstNames.Items.Clear(); 
      lstNames.Items.AddRange(names.Cast<object>().ToArray()); 
     } 
    } 
} 

我有这些控制:

  • 标签:lblName
  • 文本框:txtName的
  • 按钮:btnSummary
  • 列表框:lstNames

这两种方法是为指定的控制事件处理程序。

这里是UI:

The UI

+0

我正在使用此窗体的Windows窗体应用程序。我发布了一段代码供我参考。你能给我一个代码的例子吗? –

0

您可能需要使用该静态变量,这样,这将保存所有的输入,用于显示在未来:

确保你把这个声明为静态变量:

public static List<string> lstInputs { get; set; } 

然后你可以使用文本框的KeyDown事件处理程序,以便您可以检测键盘上输入了被按下:

private void textBox2_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (lstInputs == null) 
      lstInputs = new List<string>(); 
     if (e.KeyCode == Keys.Enter) 
     { 
      lstInputs.Add(textBox2.Text); 
      textBox2.Text = string.Empty; 
      MessageBox.Show("Message has been saved."); 
     } 
    } 

最后,您可以使用for循环来获取所有消息。我在这里使用List,因为List是动态的,不需要声明最大尺寸是多少。但是如果你愿意,你可以使用普通的字符串数组。

相关问题