简体   繁体   中英

C# WinForms | Add Label when Button is Clicked

Honestly I don't know how to construct my questions. But my idea is, I want to copy the facebook messenger's ui in our case study. We were tasked to make a guessing game.
I don't know how I will code my idea. My plan was to add a new label everytime the send button is clicked, and the panel where the add-on labels will be added will be extended the so that the screen will appear to be sliding.

Here's a screenshot of the winform.

Here is my Initial Code for the btnSendClicked.

private void btnSend_Click(object sender, EventArgs e)
    {
        Label lblnew = new System.Windows.Forms.Label();
        lblnew.Location = new Point(50, 50);
        lblnew.Text = txtMessage.Text;
        lblnew.AutoSize = true;
        lblnew.BackColor = System.Drawing.Color.LightGray;
        lblnew.Font = new System.Drawing.Font("Microsoft JhengHei UI", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        pnlGame.Controls.Add(lblnew);
    }

You need to keep track of the labels you've rendered on the Panel, in order to manage your scrolling mechanism, which could be done by a looping algorithm:

Loop through all Label controls in pnlGame

  • If the current label's Top position is less than or equal to the Top of pnlGame , hide the label (Visible = false). The same applies for the Bottom. (remove all labels that should not be visible when scrolling), otherwise, Unhide the label to bring it back into view.

Put the above logic into a method, something like void RefreshVisiblePanelMessages()

When clicking on a button to generate a new message, add the new message as a Label to your pnlGame and then call RefreshVisiblePanelMessages(); to update the list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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