2016-02-28 60 views
1

这里是我的代码,它的工作原理。C# - 数组 - 输入名称并显示它们

除了打显示名称按钮(输入姓名后)存储在阵列后,显示文本框的滚动条跳了下来,并要拉起来看看输入的名称。

2.此外,继续输入名称后(输入很少)后,我得到换行符(在显示名称文本框中)和输入名称重复显示。它应该在最后输入的名字后面显示名称,而不必重复先前输入的名称和换行符。

任何想法是什么造成的?

我的代码:

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); 
     } 
    } 

} 
} 
+0

代码在哪里? –

+0

'这是我的代码。 - 在哪里? –

+0

对不起,刚添加它 – Prince

回答

0

对于滚动条问题,设置文本的而不是使用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); 
} 

换行,如果你按下按钮,而无需输入应该发生名字在里面。在添加文本之前测试文本的存在:

//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 
    } 
} 
+0

谢谢。工作很棒。 – Prince

+0

我该如何添加try/catch到代码? – Prince

+0

为什么和你需要一个try/catch? –

相关问题