我正在尝试创建一个客户列表。当用户插入新客户端的名称时,必须将此名称添加到列表中并显示在消息框中。预先配置的客户是Jack,Sandra,Anna,Tom和Bob。当我运行以下脚本并输入新的客户端名称时,会弹出一个没有新名称的弹出窗口。这是为什么?
private void btnAddClient_Click(object sender, EventArgs e)
{
string msg = "";
List<string> Clients = new List<string>();
Clients.Add("Jack");
Clients.Add("Sandra");
Clients.Add("Anna");
Clients.Add("Tom");
Clients.Add("Bob");
foreach (string val in Clients)
{
msg += "- " + val + "\n";
}
if (txtAddClient.Text == "")
{
MessageBox.Show("No client name has been entered!");
}
else
{
string newClient = txtAddClient.Text;
Clients.Add(newClient);
MessageBox.Show(msg);
}
}
答案 0 :(得分:3)
因为你没有在文本框中附加带有数据的msg变量。
循环遍历现有客户端并附加变量但是一旦确定文本框不为空,就将内容添加到列表并显示msg变量。您需要使用输入的数据附加msg变量。
参见@Tisho的代码示例如何实现它 - 不想将他的代码复制为我自己的代码
答案 1 :(得分:1)
private void btnAddClient_Click(object sender, EventArgs e)
{
string msg = "";
List<string> Clients = new List<string>();
Clients.Add("Jack");
Clients.Add("Sandra");
Clients.Add("Anna");
Clients.Add("Tom");
Clients.Add("Bob");
if (txtAddClient.Text == "")
{
MessageBox.Show("No client name has been entered!");
}
else
{
string newClient = txtAddClient.Text;
Clients.Add(newClient);
// this is where you want to join your string
// AFTER you add the new client to the list
foreach (string val in Clients)
{
msg += "- " + val + "\n";
}
MessageBox.Show(msg);
}
}
答案 2 :(得分:0)
更新:
private List<string> Clients = new List<string>(){ "Jack", "Sandra", "Anna", "Tom", "Bob"};
private void btnAddClient_Click(object sender, EventArgs e)
{
string msg = "";
if (txtAddClient.Text == "")
{
MessageBox.Show("No client name has been entered!");
}
else
{
string newClient = txtAddClient.Text;
Clients.Add(newClient);
foreach (string val in Clients)
{
msg += "- " + val + "\n";
}
MessageBox.Show(msg);
}
}
答案 3 :(得分:0)
你必须做
msg += txtAddClient.Text;
然后
MessageBox.Show(msg);
答案 4 :(得分:0)
public partial class Form1 : Form
{
List<string> Clients = new List<string>();
public Form1()
{
InitializeComponent();
Clients.Add("Jack");
Clients.Add("Sandra");
Clients.Add("Anna");
Clients.Add("Tom");
Clients.Add("Bob");
}
private void btnAddClient_Click(object sender, EventArgs e)
{
if (txtAddClient.Text == "")
{
MessageBox.Show("No client name has been entered!");
}
else
{
string msg = "";
string newClient = txtAddClient.Text;
Clients.Add(newClient);
foreach (string val in Clients)
{
msg += "- " + val + "\n";
}
MessageBox.Show(msg);
}
}
}