I made a small text editor that saves text from a RichTextBox into an .rtf file, but whenever I click the open menu option it opens the savefile dialog box. I cannot figure out why can anyone help me out?
Here are the names for the menu dialog items.
MenuStrip: menuStrip1
Save: saveMenu
Open: openMenu
RichTextBox: richTextBox1
here is the code that I am working on below…
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//save the file
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
// Text from the rich textbox rtfMain
string str = richTextBox1.Text;
// Create a new SaveFileDialog object
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
// Available file extensions
dlgSave.Filter = "Rich Text Format (.rtf)|*.rtf";
// SaveFileDialog title
dlgSave.Title = "Save";
// Show SaveFileDialog
if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
{
richTextBox1.SaveFile(dlgSave.FileName);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
private void openMenu_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
using (var of = new OpenFileDialog())
{
of.DefaultExt = "*.rtf";
of.Filter = "RTF Files|*.rtf";
if (of.ShowDialog() == DialogResult.OK)
richTextBox1.Rtf = System.IO.File.ReadAllText(of.FileName);
}
}
}
}
I’m assuming your openMenu is a child item on the menuStrip1; thus when you click it, the the menuStrip1_ItemClicked event is raised, and that’s exactly where you have your code to open a Save dialog.
You should probably get rid of the openMenu_ItemClicked method, and instead have a single menuStrip1_ItemClicked method wired up the menuStrip1’s ItemClicked event, and in that method you can determine what item was clicked and what to do accordingly.
So in your menuStrip1_ItemClicked method, you could do something like…
P.S. you can debug to see the flow of execution, and you’ll probably see that the menuStrip1 ItemClicked event is being raised first, and that code being executed first.