简体   繁体   English

C#-数组-输入名称并显示它们

[英]C# - Arrays - Enter Names and display them

here is my code that works. 这是我的代码。

1. Except after hitting Show Names button (after entering names) that stored in Array, display textbox scroll bar jump down and have to pull it up to see entered names. 1.除了点击存储在Array中的Show Names按钮(输入名称之后)外,显示文本框滚动条向下跳,必须向上拉才能看到输入的名称。

2. Also, after I continue entering names(after entering few), I get line breaks (in show Names textbox) and entered names are shown repeated. 2.另外,在我继续输入名称(输入几个)之后,出现换行符(在“显示名称”文本框中),并且输入的名称会重复显示。 It should display the names after the last entered one without repeating the previously entered names and line breaks. 它应该在最后输入的名称之后显示名称,而不重复先前输入的名称和换行符。

Any ideas what is causing it? 任何想法是什么原因造成的?

my code: 我的代码:

namespace Arrays
{
public partial class frmMain : Form
{


    public frmMain()
    {
        InitializeComponent();
    }


    //initialize the Array
    string[] names = new string[100];

    int index = 0;


    //Enter  Names up to 100 and store them in array
    private void btnEnterName_Click(object sender, EventArgs e)
    {
        if (index < names.Length)
        {
            names[index++] += txtName.Text;
            txtName.Clear();
        }
        else
        {
            // array 'full'
        }
    }

    //Display stored Names in Array using foreach loop in multiline textbox
    private void btnShowNames_Click(object sender, EventArgs e)
    {
        txtName.Clear();
        foreach (string item in names)
        {
            txtNames.AppendText(item + Environment.NewLine);
        }
    }

}
}

For the scrollbar problem, setting the Text instead of using AppendText will resolve the issue: 对于滚动条问题,设置Text而不使用AppendText将解决此问题:

//Display stored Names in Array using foreach loop in multiline textbox
private void btnShowNames_Click(object sender, EventArgs e)
{
    string allNames = "";
    foreach (string item in names)
    {
        allNames += item + Environment.NewLine;
    }
    txtNames.Text = allNames;

    // or more advanced
    //txtNames.Text = string.Join(names, Environment.NewLine);
}

Line breaks should happens if you hit the button without entering a name in it. 如果您在未输入名称的情况下按了按钮,则会出现换行符。 Test the presence of the Text before adding it: 在添加之前测试文本的存在:

//Enter  Names up to 100 and store them in array
private void btnEnterName_Click(object sender, EventArgs e)
{
    // remove spaces at start and end
    string trimedName = txtName.Trim();
    bool nameExist = !string.IsNullOrEmpty(trimedName);
    bool notHittingMaxName = index < names.Length;
    if (nameExist && notHittingMaxName)
    {
        names[index++] += trimedName;
        txtName.Clear();
    }
    else
    {
        // array 'full' or empty name
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM