如何从文本框中获取字符串值并将其存储在数组字符串中?单击摘要按钮后,它会在列表框中将列表显示为列表。
例如,用户输入" Tom"在文本框中。点击进入! Tom存储在数组中 用户输入" 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]);
}
答案 0 :(得分:1)
您没有指定您正在编写的应用程序类型:WinForms,WPF等。
您也没有展示您的编码工作。
如果没有为您提供完整的代码,建议您查找:
通常,文本框具有Text
属性,您也可以订阅文本框的相应事件,以便在用户点击Enter
时捕获。您可以通过文本框的Text
属性读取输入的名称,并将其添加到列表中,例如List<string>
然后通过将Text
属性设置为空字符串来清除文本框。
当用户点击摘要按钮时,您可以使用Items
方法通过Add()
属性将列表中的元素添加到列表框中。
这是我要去的方向。你可以谷歌休息。
更新#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());
}
}
}
我有这些控件:
这两个方法是指定控件的事件处理程序。
以下是用户界面:
答案 1 :(得分:0)
您可能需要使用静态变量,以便将来保存所有输入以供显示:
确保将其声明为静态变量:
public static List<string> lstInputs { get; set; }
然后你可以使用Textbox的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是动态的,不需要声明这个的最大大小。但是如果你愿意,可以使用普通的字符串数组。