I''m devoloping a multi tabbed notepad application. How do I perform a save all function on all the tabs on the application without opening a SaveFileDialog after I save the tabs. The method shown below works but it opens a SaveFileDialog for all the tabs.
string strfilename;
RichTextBox rtb = null;
private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
{
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
if (rtb != null)
{
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
rtb.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
}
}
I tried it like this as well but only last saved tab gets saved
private void saveAllToolStripMenuItem_Click(object sender, EventArgs e)
{
TabControl.TabPageCollection pages = tabControl1.TabPages;
foreach (TabPage page in pages)
{
rtb = page.Controls[0] as RichTextBox;
if (rtb != null)
{
rtb.SaveFile(strfilename, RichTextBoxStreamType.PlainText);
}
}
}
This is my individual save function
public void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sv = new SaveFileDialog();
sv.Filter = "Text Document(*.txt)|*.txt|All Files(*.*)|*.*";
if (sv.ShowDialog() == DialogResult.OK)
GetRichTextBox().SaveFile(sv.FileName, RichTextBoxStreamType.PlainText);
this.Text = sv.FileName;
strfilename = sv.FileName;
autosave(sv.FileName);
}
Though this is old,
You can save the file name for the tab with it's Name,
e.g.
Tabpage tb = new TabPage();
RichTextBox rtb = new RichTextBox();
tb.Name = Path.GetFullPath(ofd.FileName); // <--- 'ofd' is the OpenFileDialog
tb.Controls.Add(rtb);
tb.Text = Path.GetFileName(ofd.FileName); // <--- This sets the tab's text to the file's name, rather than the full path.
tabControl1.TabPages.Add(tb);
You can put that snippet of code into the part where you actually open a file.
So, when the user (Or you) presses the Save All button, this snippet of code should be used:
foreach (TabPage tb in tabControl1.TabPages)
{
if (File.Exists(tb.Name))
{
File.WriteAllText(tb.Name, ((RichTextBox)tb.Controls[0]).Text); // <--- You can optionally save the RTF!
}
else if (!File.Exists(tb.Name))
{
saveFileDialog(sender, e);
}
}
saveFileDialog(sender, e) is the Link to your 'Save As' dialog, so that the user may save the individual files that either were deleted and don't exist anymore, or files that never existed all together. (Like if the user presses 'New', and it creates a new tab with a RichTextBox in it, the name would not exist as a file.)
For your 'New Tab' button,
TabPage tb = new TabPage();
RichTextBox rtb = new RichTextBox();
tb.Name = "New.Txt";
tb.Text = "New.Txt";
tb.Controls.Add(rtb);
tabControl1.TabPages.Add(tb);
Optionally, you can create an integer to watch how many 'New.Txt' are created, and instead of it displaying 'New.Txt', it would display 'New*5.Txt' if there were already four tabs before it. (I won't go too far into that.)
If you have any questions, feel free to ask.
Related
I'm using Visual Studio, WPF, C#, XAML.
My program has Input and Output buttons.
Input uses OpenFileDialog.
Output uses SaveFileDialog.
I need each button to remember its last used directory, but RestoreDirectory = true causes both button's last directory to be the same. Each does not remember it's own directory separate.
// Input Button
//
private void btnInput_Click(object sender, RoutedEventArgs e)
{
// Open 'Select File' Window
Microsoft.Win32.OpenFileDialog selectFile = new Microsoft.Win32.OpenFileDialog();
// Remember Last Dir
selectFile.RestoreDirectory = true;
// Show Window
Nullable<bool> result = selectFile.ShowDialog();
// Display Path
if (result == true)
{
tbxInput.Text = selectFile.FileName;
}
}
// Output Button
//
private void btnOutput_Click(object sender, RoutedEventArgs e)
{
// Open 'Save File' Window
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
// Remember Last Dir
saveFile.RestoreDirectory = true;
// Show Window
Nullable<bool> result = saveFile.ShowDialog();
// Display Path
if (result == true)
{
tbxOutput.Text = saveFile.FileName;
}
}
I have created a notepad with a tabbed interface. It is a c# winform application. Now, what I want is this - if the file does not exist anymore, deleted by another program then if I click the related tab, it should show a message that "the file does not exist" and it should close the tab.
private string FolderPath = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // location of document folder
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
{
if (tabControl1.TabCount == 0)
{
return;
}
else
{
TabPage tpp = tabControl1.SelectedTab;
this.FileOnly = tpp.Text + ".txt"; // I used tab names without extension, that's why adding it back
String str = tpp.Text;
string CorrFolderPath = FolderPath.Replace(#"\", #"\\");
string FolderPathcomplete = CorrFolderPath + "\\My_Note\\"; // this is the location of saving files; the folder contents appear as list box entries in the program
string filename = FolderPathcomplete + FileOnly;
if (str.Contains("New Document"))// the new tabs which are not yest saved has the name New Document 1, 2 etc.
{
return;
}
else
{
if (File.Exists(filename))
{
return;
}
else
{
MessageBox.Show("File does not exist! Closing the tab.");
var tabPage = tabControl1.TabPages[str];
tabControl1.TabPages.RemoveByKey(str);
}
}
}
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage("New Document" + count); //creates a new tab page
tp.Name = "New Document" + count;
RichTextBox rtb = new RichTextBox(); //creates a new richtext box object
tp.Controls.Add(rtb); // adds rich text box to the tab page
tabControl1.TabPages.Add(tp); //adds the tab pages to tab control
tabControl1.SelectedTab = tp;
tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged; // it will check whether tab file exists or not
this.FileName = string.Empty;
count++;
}
Consider using a FileSystemWatcher -- where on creation of a new tab, you create a new watcher and monitor for any changes.
See this article for more information:
https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx
I'm not sure what to title this, so that's why I used quotations. Bare in mind, I'm very new to C#.
I'm just creating a basic Notepad in C# VS.
using System;
using System.IO;
using System.Windows.Forms;
namespace Notepad_Project
{
public partial class notepadMain : Form
{
public notepadMain()
{
InitializeComponent();
}
private RichTextBox GetRichTextBox()
{
RichTextBox rtb = null; // initialising null
TabPage tp = tabControl1.SelectedTab;
if (tp!=null)
{
rtb = tp.Controls[0] as RichTextBox;
}
return rtb;
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
TabPage tp = new TabPage("New Document"); // Allows for new tab creation
RichTextBox rtb = new RichTextBox(); // Allows for new richtext box object
rtb.Dock = DockStyle.Fill; // Applys dock with RTB
tp.Controls.Add(rtb); // Tabs RTB
tabControl1.TabPages.Add(tp); // Add tabs to tab control
}
private void cutToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Cut();
}
private void copyToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Copy();
}
private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
{
GetRichTextBox().Paste();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream;
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
if((myStream=openFileDialog1.OpenFile())!=null) {
string filename = openFileDialog1.FileName;
string readfiletext = File.ReadAllText(filename);
TabPage tp = new TabPage("New Document");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
rtb.Text = readfiletext;
}
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog savefile = new SaveFileDialog();
RichTextBox rtb = new RichTextBox();
savefile.Filter = "Plain Text (.txt)|*.txt|Batch File (.bat)|*.bat|Visual Studio (.vbs)|*.vbs";
if (savefile.ShowDialog() == DialogResult.OK) {
rtb.SaveFile(savefile.FileName, RichTextBoxStreamType.PlainText);
}
}
}
}
I basically, in short want to use RichTextBox rtb = New RichTextbox(); once and be able to declare it everywhere else, like a global variable. I've seen that you can use classes for this, but I'm unsure on how to implement it this way. If you notice, you can see that I have to declare RichTextBox rtb = New RichTextBox(); everytime I add a new function or so on.
If I was to remove the RichTextBox rtb = New RichTextbox(); from this section:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog savefile = new SaveFileDialog();
RichTextBox rtb = new RichTextBox();
savefile.Filter = "Plain Text (.txt)|*.txt|Batch File (.bat)|*.bat|Visual Studio (.vbs)|*.vbs";
if (savefile.ShowDialog() == DialogResult.OK) {
rtb.SaveFile(savefile.FileName, RichTextBoxStreamType.PlainText);
}
}
I will then obtain this error too: The name 'rtb' does not exist in the current context
So, how would I implement and use this globally in C#? This is also so I can learn how to shorten certain things and keep it clean, efficient and tidy.
You creating controls dynamically so in your case you don't need to remove that line. You need to GET active tab rich text control and you have method for that.
Of course you can replace GetRichTextBox() method with property like this:
private RichTextBox ActiveRichTextBox
{
get
{
RichTextBox rtb = null; // initialising null
TabPage tp = tabControl1.SelectedTab;
if (tp!=null)
{
rtb = tp.Controls[0] as RichTextBox;
}
return rtb;
}
}
and use it in your code like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog savefile = new SaveFileDialog();
savefile.Filter = "Plain Text (.txt)|*.txt|Batch File (.bat)|*.bat|Visual Studio (.vbs)|*.vbs";
if (savefile.ShowDialog() == DialogResult.OK) {
ActiveRichTextBox.SaveFile(savefile.FileName, RichTextBoxStreamType.PlainText);
}
}
Not sure how to implement this, i am not using SaveFileDialog which i have seen uses OverWritePrompt = true cant seem to get that to work for me.
I am using WPF.
The structure:-
I have a textBox called filePathBox - This contains a file path used from opening an: OpenFileDialog
private void fileBrowser_Click(object sender, RoutedEventArgs e)
{
//Firstly creating the OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//Setting the filter for the file extension of the files as well as the default extension
dlg.DefaultExt = ".txt";
dlg.Filter = "All Files|*.*";
//Display the dialog box by calling the ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
//Grab the file you selected and display it in filePathBox
if (result == true)
{
//Open The document
string filename = dlg.FileName;
filePathBox.Text = filename;
}
}
You can then click a button and the .txt file displays in a textBox called textResult
private void helpfulNotes_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(filePathBox.Text) && System.IO.Path.GetExtension(filePathBox.Text).ToLower() == ".txt")
{
textResult.Text = File.ReadAllText(filePathBox.Text);
}
if (string.IsNullOrWhiteSpace(filePathBox.Text))
{
MessageBox.Show("Please choose a file by clicking on the folder Icon :(");
}
}
Once you have made changes to that text in 'textResult' i have a button to save the text back to the file path that was originally loaded using the OpenFileDialog
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
At the moment it all saves fine, only it doesn't prompt the user saying are you sure you want to overwrite the file.
At the moment i could
load a file for the purpose of this named TestNote.txt into the
filePathBox
Type some text in textResult before even clicking to display the
file
Click save and it would just overwrite TestNote.txt with the text i
just entered without even warning me
Hopefully i have explained this adequately and provided all the code you need
Just add a messagebox to show your alert message before writing to the text file.
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
if(MessageBox.Show("are you sure you want to overwrite the file.", "Alert", MessageBoxButtons.YesNo)==DialogResult.Yes)
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
Well, OverWritePrompt is a SaveFileDialog property, which you're not using: you're always using File.WriteAllText(), which always overwrites the target file.
You want to provide a Save function that saves an earlier opened file without prompt, a Save As function that prompts the user for a new filename and also call Save As when saving a new file.
This is implemented like this, pseudo:
private string _currentlyOpenedFile;
public void FileOpen_Click(...)
{
var openFileDialog = new ...OpenFileDialog();
if (openFileDialog.ShowDialog())
{
// Save the filename when opening a file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
public void FileNew_Click(...)
{
// Clear the filename when closing a file or making a new file.
_currentlyOpenedFile = null;
}
public void FileSave_Click(...)
{
if (_currentlyOpenedFile == null)
{
// New file, treat as SaveAs
FileSaveAs_Click();
return;
}
}
public void FileSaveAs_Click(...)
{
var saveFileDialog = new ...SaveFileDialog();
if (openFileDialog.ShowDialog())
{
// Write the file.
File.WriteAllText(text, openFileDialog.FileName);
// Save the filename after writing the file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
Here you'll be leveraging the SaveFileDialog's functionality which prompts the user whether they want to overwrite an already existing file.
while i am trying to implement font menu item in notepad ,
im not getting text changed , is there any mistake in my code
this is my code
private void fontMenuItem_Click(object sender, EventArgs e)
{
FontDialog objFontForm = new FontDialog();
objFontForm.ShowDialog();
}
Here's a really simple example taken from DotNetPearls
//Create FontDialog instance
FontDialog fontDialog1 = new FontDialog();
// Show the dialog.
DialogResult result = fontDialog1.ShowDialog();
// See if OK was pressed.
if (result == DialogResult.OK)
{
// Get Font.
Font font = fontDialog1.Font;
// Set TextBox properties.
this.textBox1.Text = string.Format("Font is: {0}", font.Name);
this.textBox1.Font = font;
}