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);
}
}
Related
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.
I am populating a listbox with a file. This can be done by two methods, the open file dialog command initiated by a button press and a drag/drop action into the listbox. I want to pass on the file path (for the file in the listbox) to other areas of my code, for example the DataContext that reads the file in the listbox. Basically I want the file path to automatically update when the listbox is populated. I am new to C# so sorry if I haven't explained myself properly or provided enough information. The code for populating my listbox (named FilePathBox) and the 'Run' button is as follows:
private void BrowseButton_Click(object sender, RoutedEventArgs e)
{
var openFileDialog = new Microsoft.Win32.OpenFileDialog();
//openFileDialog.Multiselect = true;
openFileDialog.Filter = "Csv files(*.Csv)|*.Csv|All files(*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (openFileDialog.ShowDialog())
{
FilePathBox.Items.Clear();
foreach (string filename in openFileDialog.FileNames)
{
ListBoxItem selectedFile = new ListBoxItem();
selectedFile.Content = System.IO.Path.GetFileNameWithoutExtension(filename);
selectedFile.ToolTip = filename;
FilePathBox.Items.Add(selectedFile);
}
}
}
private void FilesDropped(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
FilePathBox.Items.Clear();
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
foreach (string droppedFilePath in droppedFilePaths)
{
ListBoxItem fileItem = new ListBoxItem();
fileItem.Content = System.IO.Path.GetFileNameWithoutExtension(droppedFilePath);
fileItem.ToolTip = droppedFilePath;
FilePathBox.Items.Add(fileItem);
}
}
}
private void RunButton_Click(object sender, RoutedEventArgs e)
{
DataContext = OldNewService.ReadFile(#"C:\Users\Documents\Lookup Table.csv");
}
I added a comment, but I think what you need a way to get the selected file path when the RunButton is clicked, so just add this to your RunButton_Click method,
private void RunButton_Click(object sender, RoutedEventArgs e)
{
string selection = (string)FilePathBox.SelectedItem;
DataContext = OldNewService.ReadFile(selection);
}
This is the code for making a new tab with a rich text box in it and selecting the current richtextbox.
private RichTextBox GetRichTextBox()
{
RichTextBox rtb = 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");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
tp.Controls.Add(rtb);
tabControl1.TabPages.Add(tp);
}
I need to be able to add a context menu to the richtextbox, with cut, copy, paste and other controls I may need. I am not sure how to go about doing this.
Usually you could add a ContextMenuStrip to your form, use the designer to define the menu items and then go to the RichTextBox properties and assign the ContextMenuStrip instance to the ContextMenuStrip property of the RichTextBox.
However you could create the same interface dynamically using code:
TabPage tp = new TabPage("New Document");
RichTextBox rtb = new RichTextBox();
rtb.Dock = DockStyle.Fill;
ContextMenuStrip ctx = new ContextMenuStrip();
ctx.Items.Add(new ToolStripMenuItem("Cut",null, cutClick));
ctx.Items.Add(new ToolStripMenuItem("Copy", null, copyClick))
ctx.Items.Add(new ToolStripMenuItem("Paste", null, pasteClick));
// Add other menu items as you need
rtb.ContextMenuStrip = ctx;
.....
void cutClick(object sender, EventArgs e)
{
RichTextBox rtb = sender as RichTextBox;
if(rtb.SelectedText.Length > 0)
rtb.Cut();
}
void copyClick(object sender, EventArgs e)
{
RichTextBox rtb = sender as RichTextBox;
if(rtb.SelectedText.Length > 0)
rtb.Copy();
}
void pasteClick(object sender, EventArgs e)
{
RichTextBox rtb = sender as RichTextBox;
DataFormats.Format textFormat = DataFormats.GetFormat(DataFormats.Text);
if(rtb.CanPaste(textFormat))
rtb.Paste();
}
When user changes background color for example, the Settings.settings file is modified. And it works.
But the application doesn't change it's background color after user clicks OK.
It works only when I close and build the application again.
How can I reload my form or user control on button click? (Tried with .Refresh(), but it doesn't work)
private void refreshSettings()
{
this.BackColor = Properties.Settings.Default.bgdColor;
this.Font = Properties.Settings.Default.fontType;
this.ForeColor = Properties.Settings.Default.fontColor;
}
private void Settings_Load(object sender, EventArgs e)
{
refreshSettings();
bgdColorLBL.BackColor = Properties.Settings.Default.bgdColor;
fontColorLBL.BackColor = Properties.Settings.Default.fontColor;
fontTypeLBL.Font = Properties.Settings.Default.fontType;
fontTypeLBL.Text = Properties.Settings.Default.fontType.Name;
}
private void okBTN_Click(object sender, EventArgs e)
{
LeagueUC lg = new LeagueUC();
InitializeComponent();
this.Close();
}
private void bgdColorLBL_Click(object sender, EventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.Color = Properties.Settings.Default.bgdColor;
if (dlg.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.bgdColor = dlg.Color;
Properties.Settings.Default.Save();
bgdColorLBL.BackColor = dlg.Color;
}
}
Run whatever code you have that sets the control's properties at start up from the settings file.
e.g.
private void bgdColorLBL_Click(object sender, EventArgs e)
{
ColorDialog dlg = new ColorDialog();
dlg.Color = Properties.Settings.Default.bgdColor;
if (dlg.ShowDialog() == DialogResult.OK)
{
Properties.Settings.Default.bgdColor = dlg.Color;
Properties.Settings.Default.Save();
Settings_Load(null, null);
}
}
On the button click event, just load the backcolor from your settings file. Something like:
this.BackColor = Properties.Settings.Default.Color;
You can create binding for it. With a little tricks the binding can even allow the immediate interface language switching.
try this, this changes background color of form in color that you chose from ColorDialog:
private void button2_Click(object sender, EventArgs e)
{
ColorDialog dlg = new ColorDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
this.BackColor = System.Drawing.Color.FromName(dlg.Color.Name);
}
}
I have a windows form application I have a button that opens the SaveFileFrom dialog
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog savefileDialog1 = new SaveFileDialog();
savefileDialog1.ShowDialog();
}
I was wondering how I could put the file that is chosen in a text box even like so
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
UPDATE* Ok, well since the user might want to open more than one file to save I wanted to take off my button SaveFileFrom and instead make the textbox run through the OpenFileDialog when clicked.
Also, is their a way to make a text link instead of a button?
Like I want a text link to add another text box/
Try this
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog savefileDialog1 = new SaveFileDialog();
if (savefileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = savefileDialog1.Filename;
}
}
The filename selected will be saved in SaveFileDialog.FileName
example:
private void button1_Click(object sender, EventArgs e)
{
SaveFileDialog SvDlg = new SaveFileDialog();
if (SvDlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = SvDlg.FileName;
}
else
{
MessageBox.Show("No file selected.");
}
}