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();
}
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'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);
}
}
Everytime the button's click event get fired, the label (or any other control) in panel gets overwrite by the new one! Here is the button event.
protected void Button3_Click(object sender, EventArgs e)
{
Label lbl = new Label();
lbl.ID = "name";
lbl.Text = Profession.SelectedItem.ToString();
Panel1.Controls.Add( lbl);
}
It everytime remove the previous label and add new label with the selected item in DropDownList
Label is getting initialized on every click that is the problem
protected void Button3_Click(object sender, EventArgs e)
{
Label lbl = new Label();//here on every click new label initialized
lbl.ID = "name";
lbl.Text = Profession.SelectedItem.ToString();
Panel1.Controls.Add(lbl);
}
Replace above code by
Label lbl = new Label();
protected void Button3_Click(object sender, EventArgs e)
{
lbl.ID = "name";
lbl.Text = Profession.SelectedItem.ToString();
if(!Panel1.Controls.Contains(lbl)) //Check here if label already added
Panel1.Controls.Add(lbl);
}
Look at the scope of your Label. You are creating a new instance of Label on every click. Take this on class level
Label lbl = new Label();
I'm designing an article editor for my company and I'd like to be able to show a live preview of the article in a separate WebBrowser window/control. The WebBrowser control needs to refresh the page every time the user changes anything in one of the fields for the article.
Previously, I had the WebBrowser control on the same form, but for space reasons, I had to break it out onto a separate form and access it using a button on the editor form. However, since I moved that control into a separate form, the WebBrowser gains focus on every refresh, meaning I can type one character and then I have to click back to the textbox I was typing in.
My question: Is there a way to refresh that preview page in the background without it stealing the focus so that I can update the preview to reflect what the user is typing without interrupting the user while typing?
Here are the methods for showing and refreshing the preview, respectively:
private void buttonShowPreview_Click(object sender, EventArgs e)
{
if (buttonShowPreview.Tag == null)
{
Form browserForm = new Form();
browserForm.FormClosing += new FormClosingEventHandler(delegate(Object form, FormClosingEventArgs args)
{
if (args.CloseReason == CloseReason.UserClosing)
{
args.Cancel = true;
browserForm.Hide();
previewShowing = false;
}
});
browserForm.Size = new System.Drawing.Size(1024, 768);
browserForm.DesktopLocation = new System.Drawing.Point(0, 0);
browserForm.Text = "Article Preview";
preview = new WebBrowser();
browserForm.Controls.Add(preview);
preview.Dock = DockStyle.Fill;
preview.Navigate("about:blank");
buttonShowPreview.Tag = browserForm;
}
Form previewForm = buttonShowPreview.Tag as Form;
previewForm.Show();
previewShowing = true;
RefreshPreview();
}
private void RefreshPreview(string jumpToAnchor)
{
if (preview != null)
{
preview.Document.OpenNew(true);
preview.Document.Write(structuredContent.GetStructuredContentHTML(content, jumpToAnchor, false));
preview.Refresh();
}
}
Based on the answer by Robberechts here, try disabling the parent Form, updating your WebBrowser, then re-enabling the parent Form again in the DocumentCompleted() event:
private void buttonShowPreview_Click(object sender, EventArgs e)
{
if (buttonShowPreview.Tag == null)
{
Form browserForm = new Form();
browserForm.FormClosing += new FormClosingEventHandler(delegate(Object form, FormClosingEventArgs args)
{
if (args.CloseReason == CloseReason.UserClosing)
{
args.Cancel = true;
browserForm.Hide();
}
});
preview = new WebBrowser();
preview.DocumentCompleted += preview_DocumentCompleted; // handle the DocumentCompleted() event
browserForm.Controls.Add(preview);
preview.Dock = DockStyle.Fill;
preview.Navigate("about:blank");
buttonShowPreview.Tag = browserForm;
}
Form previewForm = buttonShowPreview.Tag as Form;
previewForm.Size = new System.Drawing.Size(1024, 768);
previewForm.DesktopLocation = new System.Drawing.Point(0, 0);
previewForm.Text = "Article Preview";
RefreshPreview();
previewForm.Show();
}
private void RefreshPreview(string jumpToAnchor)
{
if (preview != null && preview.Parent != null)
{
preview.Parent.Enabled = false; // disable parent form
preview.Document.OpenNew(true);
preview.Document.Write(structuredContent.GetStructuredContentHTML(content, jumpToAnchor, false));
preview.Refresh();
}
}
private void preview_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = sender as WebBrowser;
if (wb.Parent != null)
{
wb.Parent.Enabled = true; // re-enable parent form
}
}
Here is my code
protected void Button1_Click(object sender, EventArgs e)
{
Panel panel1 = new Panel();
Label newLabel = new Label();
newLabel.ID = "lbltest";
newLabel.Text = "my new label..";
panel1.Controls.Add(newLabel);
}
I cant see the my label text when i click the button
Any help appreciate
Thanks
You must add your panel inside of any control which exists on your page.
You have to add the Panel to some control in your web page or your top level form element if you don't have anywhere else to put it.
protected void Button1_Click(object sender, EventArgs e)
{
Panel panel1 = new Panel();
Label newLabel = new Label();
newLabel.ID = "lbltest";
newLabel.Text = "my new label..";
panel1.Controls.Add(newLabel);
this.Form.Controls.Add(panel1); // YOU ARE MISSING THIS
}
You need to add the Panel to the page:
protected void Button1_Click(object sender, EventArgs e)
{
Panel panel1 = new Panel();
Label newLabel = new Label();
newLabel.ID = "lbltest";
newLabel.Text = "my new label..";
panel1.Controls.Add(newLabel);
//Do this
SomeControlOnYourPage.Controls.Add(panel1);
}