skip to Main Content

So, I’m trying to make a really basic word processor program in Visual Studio 2022 for a class I’m taking. One of the features I want to include is the ability to change the font of the document via some tool strip menu items (which for expedience I will refer to as "font buttons") at the top. I’ve made a click event method connected to each of the font buttons, and I want it to call upon the text of the font button and use it to change the font of the document(txtDocument). However, I am struggling to get it to correctly retrieve the text.

For reference, here is my code:

private void fontButton_Click(object sender, EventArgs e)
{
    //call upon button clicked
    ToolStripMenuItem fontBtn = new ToolStripMenuItem();
    
    //change fontName text to name of button clicked
    fontName = fontBtn.Text.ToString();
    
    //change font of txtDocument to title of clicked button
    txtDocument.Font = new Font(fontName, fontSize);
   
    //test code to make sure the right font is retrieved
    txtDocument.Text = fontName;
}

Right now, instead of fontName changing to the text of the font button, it just sets fontName blank. I’m still somewhat new to coding, so I am certain there is something very basic I am missing.

Any help would be appreciated. Please let me know if I was unclear on anything.

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the help. I've found that replacing "New ToolStripMenuItem()" with "sender as ToolStripMenuItem()" makes it work. Thank you to AKX for making the suggestion.


  2. In the fontButton_Click event, the sender is the ToolStripButton:

    private void fontButton_Click(object sender, EventArgs e)
    {
        //call upon button clicked
        if (sender is not ToolStripButton fontBtn) return;
    
        //change fontName text to name of button clicked
        var fontName = fontBtn.Text!;
    
        //change font of txtDocument to title of clicked button
        txtDocument.Font = new Font(fontName, txtDocument.Font.Size);
    
        //test code to make sure the right font is retrieved
        txtDocument.Text = fontName;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search