如何避免每个按钮替换单词

本文关键字:替换 单词 按钮 何避免 | 更新日期: 2023-09-27 18:21:31

我正在为名为"句子生成器"的类创建一个应用程序,它应该允许用户单击提供的按钮在标签上构建句子。我没有成功地让一个按钮生成的单词在我点击另一个按钮后留在标签上。当我点击一个按钮时,它会将按钮上的单词显示在标签上。然后,当我单击另一个按钮时,该按钮上的单词会出现在标签上,但它会取代之前已经存在的单词。我需要它留在标签上,这样用户就可以通过按下多个按钮在标签上创建一个句子。这是我的应用程序代码。

namespace C3_7_Sentence_Builder
{
    public partial class sentencebuilderForm : Form
    {
        public sentencebuilderForm()
        {
            InitializeComponent();
        }
        private void resetButton_Click(object sender, EventArgs e)
        {
            sentenceoutputLabel.Text = "";
        }
        private void exitButton_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void AButton_Click(object sender, EventArgs e)
        {
            string output;
            output = AButton.Text;
            sentenceoutputLabel.Text = output;
        }
        private void a_Button_Click(object sender, EventArgs e)
        {
            string output;
            output = a_Button.Text;
            sentenceoutputLabel.Text = output;
        }
        private void anButton_Click(object sender, EventArgs e)
        {
            string output;
            output = anButton.Text;
            sentenceoutputLabel.Text = output;
        }
        private void TheButton_Click(object sender, EventArgs e)
        {
            string output;
            output = TheButton.Text;
            sentenceoutputLabel.Text = output;
        }
        private void the_Button_Click(object sender, EventArgs e)
        {
            string output;
            output = the_Button.Text;
            sentenceoutputLabel.Text = output;
        }
    }
}

如何避免每个按钮替换单词

您需要使用+=

sentenceoutputLabel.Text += output;

这样做的目的是附加字符串而不是覆盖它。

除了我的评论,我想我会把它作为一个答案发布,因为你可以删除所有单独的事件,并将所有按钮订阅到下面来做同样的事情。

private void sentence_button_clicked(object sender, EventArgs e)
{
    var button = sender as Button;
    if(button != null)
        sentenceoutputLabel.Text += button.Text;
}

唯一需要重新分配文本而不是追加文本的按钮是重置按钮。

您总是用您选择的所有文本替换标签的所有文本。您需要标签的文本才能保留,并且仅添加新文本:

sentenceoutputLabel.Text = sentenceoutputLabel.Text + output;

您可能需要添加一些空格:

sentenceoutputLabel.Text = sentenceoutputLabel.Text + " " + output;