通过按钮输入文本

时间:2017-01-05 14:59:29

标签: c# arrays visual-studio list button

我的表单上有4个按钮,我希望用户通过单击按钮上的上,下,左,右输入他的单词。

Image of the example form

用户可以通过上下来选择他的字母,数字或符号。

左右将是在这个词中来回走动。以防万一他犯了错误并转发,以防他想确认他现在的信件。

这些是变量

private string word;

private StringBuilder sb = new StringBuilder();

private char[] wordsAndLetters = { ' ', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', ',', '.', '!', '?' };

现在我们需要给按钮提供在字母等之间的选项。

    private int i;

    public Form1()
    {
        InitializeComponent();
        tbOutput.Text = word;         
    }

    private void btnUp_Click(object sender, EventArgs e)
    {
        //We don't want the i to go above the array
        if (i <= 39)
        {
            i = i + 1;
        }
        tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);      
    }

    private void btnDown_Click(object sender, EventArgs e)
    {
        //We don't want the i to go below the array
        if (i > 0)
        {
            i = i - 1;
        }
        tbOutput.Text = word + Convert.ToString(wordsAndLetters[i]);
    }

    private void btnRight_Click(object sender, EventArgs e)
    {
        tbOutput.Text = word;
        sb.Append(wordsAndLetters[i]);
        word = sb.ToString();
        i = 0;
        tbOutput.Clear();
        tbOutput.Text = word;
    }

    private void btnLeft_Click(object sender, EventArgs e)
    {
        int lengthword = sb.Length;
        sb.Remove(lengthword -1, 1);
        word = sb.ToString();
        tbOutput.Clear();
        tbOutput.Text = word;
    }
}

这就是我现在所拥有的,它有效,但并非完美无瑕。你们有什么办法让我现在的节目更好吗?

1 个答案:

答案 0 :(得分:0)

您无法在技术上添加到现有字符串,因为它们是不可变的。相反,这里有几个简单的选项:

1)每次连接新角色。

word += wordsAndLetters[i];
//Which is the same as:
//word = word + wordsAndLetters[i];

2)使用StringBuilder作为Jay在他对你的帖子的评论中提及。

StringBuilder sb = new StringBuilder();
sb.Append(wordsAndLetters[i]);
word = sb.ToString();