I’m new to C#, so please bear with me. I’ve created a Windows application and inserted code, found in a book, for creating a simple word processor. I’ve placed a ToolStrip, RichTextBox (Dock property set to Fill) and a FontDialogBox on a form. Further, I’ve created six buttons on ToolStrip and set their Text property to Copy, Paste, Bold, Italic, Normal and Font. In the ToolStrip’s Click event handler I’ve written the code:
private void toolStrip1_Click(object sender, EventArgs e)
{ //Get a valid font
Font f = richTextBox1.SelectionFont;
if (f == null){ f = richTextBox1.Font; }
//Take action depending on the text on the Button
switch (e.Button.Text)
{
case "Copy": richTextBox1.Copy();
break;
case "Paste": richTextBox1.Paste();
break;
case "Bold": richTextBox1.SelectionFont =
new Font(f.FontStyle.Bold);
break;
case "Italic": richTextBox1.SelectionFont =
new Font(f.FontStyle.Italic);
break;
case "Normal": richTextBox1.SelectionFont =
new Font(f.FontStyle.Regular);
break;
case "Font": if (fontDialog1.ShowDialog() == DialogResult.OK)
{ richTextBox1.SelectionFont = fontDialog1.Font;
}
break;
}
}
I get the following errors:
(i) ‘System.EventArgs' does not contain a definition for 'Button'
(ii) ‘System.Drawing.Font' does not contain a definition for 'FontStyle'
I’d be grateful if someone could point out what the errors mean and how I can correct them.
Posted Dec 13, 2007, 1:16 PM
Also, not picking on you Scott : ) But I just thought I would point out that the Text property of the ToolStripButton is already in string format, no need to convert it.
Scott LyslePosted Dec 13, 2007, 10:40 AM
The click event's event args don't carry the button property. Since you want to read the text value of the button, you could make your switch statement a little different and it will work:
switch(((
ToolStripButton)(sender)).Text.ToString())Posted Dec 13, 2007, 10:39 AM
If so, you should be able to access its text property. Or you could try accessing it via the "sender" parameter in your method if you can. Since the object belongs to the form though, it may just use the form as the sender however so that might not work but give it a shot.
As for the font issue, FontStyle is an enumeration. Meaning it isnt a property or normal member of the class and cant be accessed via a class object or static class reference. You can only change the FontStyle when you create a new Font. At least thats what I got from MSDN:
http://msdn2.microsoft.com/en-us/library/system.drawing.fontstyle.aspx