C# change multiple backcolor RichTextBoxes at once - c#

Been fooling around with C# and ran into something that I was stumped on. Essentially, I have multiple RichTextBoxes that I want to change backcolor of all at once with the click of a button. I know the quick and dirty way is to just:
richTextBox1.BackColor = Color.Green;
richTextBox2.BackColor = Color.Green;
...
richTextBoxn.BackColor = Color.Green;
But for something like 100+ boxes, I am trying to aim for something a little compact in terms of programming. I was looking into using a for loop to solve my problem:
var richTextBox = new RichTextBox[6];
for (var i = 1; i < 7; i++)
{
var s = new RichTextBox();
this.Controls.Add(s);
richTextBox[i].BackColor = Color.Green;
}
But when I run the code, I get an exception issue of "An unhandled exception of type 'System.NullReferenceException' occurred..."
I hoping for a way to just change the backcolor of multiple RichTextBoxes/TextBoxes at once without having to write 100+ lines of code if I want to control 100+ backcolors at once.

If you want to change ALL the richtextboxes on your form you can do this:
foreach(var rtb in this.Controls.OfType<RichTextBox>())
rtb.BackgroundColor = Color.Green;

By using var s = new RichTextBox(); you are creating a new RichTextBox in each iteration and bind them to the form/Container. What you need to do in this scenario is that, assign BackColor to the new RichTextBox in each iteration. That is;
for (int i = 1; i < 7; i++)
{
var richBox = new RichTextBox();
richBox.BackColor = Color.Green;
this.Controls.Add(richBox);
}
In this case you need not to use var richTextBox array, If you are using var richTextBox array then your code will be like this:
var richBoxArray = new RichTextBox[6];
for (var i = 1; i < 7; i++)
{
richBoxArray[i].BackColor = Color.Green;
this.Controls.Add(richBoxArray[i]);
}
Updates as Per Comment:
So the Question is that;
How to change the background color of already existing RichTextBoxes
in my form
So the answer will be :
foreach(var richBox in this.Controls.OfType<RichTextBox>())
richBox.BackgroundColor = Color.Green;

Related

Dynamically Generate Groupboxes

I'm working on an inventory program and have finished the main functionality as a command line console app. I am now working on a version for winforms. I want to enable it to dynamically generate a Groupbox that holds some textboxes. I'd rather not design 50+ lines of multiple textboxes. Keep in mind I'm rather new to programming, having started with C# a year ago. I know next to nothing on Winforms.
I've tried to use dynamic item = new Groupbox();as a similar method allowed generation of objects at runtime. In the command line app, the way it works is that based on information given, a certain amount of objects are passed into the list _AllItems. I was thinking of generating the Groupboxes by using:
private void InitializeGroupBox()
{
foreach (Product product in Product._AllItems)
{
dynamic Item = new GroupBox();
}
}
But I have the feeling I'm nowhere near the correct method. Thanks to anybody who helps.
You will need to learn a bit more, but here is what I usually do to achieve what you asked.
internal class DynamicForm : Form
{
private FlowLayoutPanel mFlowLayoutPanel;
public DynamicForm()
{
mFlowLayoutPanel = new FlowLayoutPanel();
mFlowLayoutPanel.Dock = DockStyle.Fill;
// Add to this Form
this.Controls.Add(mFlowLayoutPanel);
InitializeGroupBox();
}
private void InitializeGroupBox()
{
mFlowLayoutPanel.SuspendLayout(); // Performance
for (int i = 1; i <= 20; i++) {
var groupBox = new GroupBox();
groupBox.Text = "GroupBox #" + i;
groupBox.Size = new Size(200, 50);
var textBox = new TextBox();
textBox.Dock = DockStyle.Fill;
// Add the TextBox to GroupBox
groupBox.Controls.Add(textBox);
// Add to this Form
mFlowLayoutPanel.Controls.Add(groupBox);
}
mFlowLayoutPanel.ResumeLayout(); // after suspend, resume!
}
}

How to add subdrowdownitems to a dropdownitem?

I got a menu item, which when you press different toolstripmenu items show. But I want to add subtoolstripmenu items to a toolstripmenuitem. This is how I thought it would work:
ToolStripMenuItem[] items = new ToolStripMenuItem[10];
for (int i=0;i<10;i++)
{
items[i] = new ToolStripMenuItem();
items[i].Name = i;
items[i].Text = i;
items[i].Tag = i;
items[i].Click += new EventHandler(MenuItemClickHandler);
}
toolStripMenuItem1.DropDownItems[2].AddRange(items); //not possible
toolStripMenuItem1.DropDownItems.AddRange(items); // possible
Sadly it only works when I use toolStripMenuItem1.DropDownItems.AddRange(items); but not when I use toolStripMenuItem1.DropDownItems[2].AddRange(items);. Anyone any idea how to do this?
I dont want it to expand at the red cross, i want the green circle: http://imgur.com/a/mFWAz
LarsTech's comment is correct.
Replace the last 2 lines with:
ToolStripMenuItem subMenu = toolStripMenuItem1.DropDownItems[2] as ToolStripMenuItem;
subMenu.DropDownItems.AddRange(items);

how to add more labels according to the later input?

I don't know whether it is clear. I mean a form has an input textbox and a button. If I input 5 in the textbox and click on the button, the form will add 5 labels...
The question is I don't know it is 5 or 4 or 3……before the code is running and the input.
I don't know how to add the labels and how to define or get their names in order to use them later in the code.
I am just learning windows applications development with VS using C#....
And also this is my first ask in stackoverflow please forgive me if it is not clear. Is there anybody can help me?
let's split your entire problem into few steps of understanding:
What basically down the line, you are asking, is to how to add controls dynamically in a winform, in your case the control is label, so wrap your label creating logic in a function like below:
protected Label CreateLabel(string Id, string text)
{
Label lbl = new Label();
lbl.Name = Id;
lbl.Text = text;
return lbl;
}
Now you need to add as many labels as the number entered in a given textBox and upon a button click, so possibly something like below in button's click event:
protected void button_Clicked(object sender, EventArgs e)
{
//make sure nothing invalid string comes here
int counter = Convert.ToInt32(txtCount.text);
for(int i=0;i<counter;i++)
{
var lbl = CreateLabel("rand"+i, "Label" +i);
container.Controls.Add(lbl);//container can be your form
}
}
Now the basic problem in winforms you will face, will be about the positioning of these dynamically added labels. The most simple way to go about it is to add your labels to winforms FlowLayoutPanel. It automatically aligns the controls. There are other layout controls available aswell. so do this :
drag and drop a FlowLayoutPanel on your form and give it the name "container", rest assured
For example:
for(var i=0; i<N; i++ ) {
var l= new Label();
l.Text = "some name #" + i.ToString();
l.Width = 200;
l.Location = new Point(30, 20);
parent.Controls.Add(l);
}
You can use this as:
Label[] arrLabel;
int num = 0;
int.TryParse(textBox1.Text, out num);
arrLabel = new Label[num];
for (int i = 0; i < num; i++)
{
arrLabel[i] = new Label();
arrLabel[i].Text = "Label #" + (i+1);
arrLabel[i].Width = 20;
arrLabel[i].Location = new Point(30+10*(i+1), 20);
this.Controls.Add(arrLabel[i]);
}

How to change checkbox text in checkboxlist? I tried but got error message

I work on windows application. It has one form in application which displays check boxes in check box list, here is the screen shot of form
It's single from of my application which i display in different languages And also my windows application is made in multiple languages Like English, German, Japanese etc..
My problem is that how to display translated text of check box in check box list
Here is my code :
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
"Select All",
"Amplitude1",
"Amplitude2",
"Amplitude3",
"Amplitude4",
"Amplitude5",
"Amplitude6",
"Amplitude7"});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
I made a single file to translate text of form, i put that code below where LCheckBox is my file from where i translate the text of check box in check box list
this.checkedListBox1.FormattingEnabled = true;
this.checkedListBox1.Items.AddRange(new object[] {
LCheckBox.SELECTALL,
LCheckBox.Amplitude1,
LCheckBox.Amplitude2,
LCheckBox.Amplitude3,
LCheckBox.Amplitude4,
LCheckBox.Amplitude5,
LCheckBox.Amplitude6,
LCheckBox.Amplitude7});
this.checkedListBox1.Location = new System.Drawing.Point(96, 55);
this.checkedListBox1.Name = "checkedListBox1";
this.checkedListBox1.Size = new System.Drawing.Size(123, 124);
this.checkedListBox1.TabIndex = 8;
this.checkedListBox1.SelectedIndexChanged += new System.EventHandler(this.ckbselectall_CheckedChanged);
But it gives me some error message
you can ask for the language at the begining and then create the checkbox list depending on the language. u can use different if cases for each language
In code I just use the items collection to modify the desired item.
So lets say you have a form with a button on it. When the button is clicked
you want to add one to all the items in the list, then the code to do that
would look as found below assuming that the listbox was named "_list" and
the button was named "_button."
private void FillList()
{
_list.BeginUpdate();
_list.Items.Clear();
for(int i =0 ; i <=9; i++)
_list.Items.Add(i);
_list.EndUpdate();
}
private void _button_Click(object sender, System.EventArgs e)
{
_list.BeginUpdate();
ListBox.ObjectCollection items = _list.Items;
int count = items.Count;
for(int i = 0; i < count; i++)
{
int integerListItem = (int)items[i];
integerListItem ++;
// --- Update The Item
items[i] = integerListItem;
}
_list.EndUpdate();
}

C#: Paste RTF in RichTextBox but keep coloring and formatting (i.e: bold, underline, etc)

Is it possible to paste text into a Rich Text Box, while keeping the font being used in the Rich Text Box for the pasted content ?
In other words, I'd like to copy something from Word that is formated (i.e: a text that uses a font X and is underlined and in blue), and then paste it in my RichTextBox.
I would like the pasted content to have the same font as that of my RichTextBox but keep its original coloring and underlining.
Is such a thing possible ?
I use winforms.
Thanks
This is not possible out of the box. But you can do something like this:
public void SpecialPaste()
{
var helperRichTextBox = new RichTextBox();
helperRichTextBox.Paste();
for(int i=0;i<helperRichTextBox.TextLength;++i)
{
helperRichTextBox.SelectionStart = i;
helperRichTextBox.SelectionLength = 1;
helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size,helperRichTextBox.SelectionFont.Style);
}
richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}
This changes the font of the pasted RTF to that of the character preceding the caret position at the time of the paste.
I assume that will get problematic pretty fast, if the text you paste is large(er). Additionally, this can be optimized in a way, that it sets the font only once for all characters in a row with the same base font as Hans suggests.
Update:
Here is the optimized version, that sets the font for a connected set of characters with the same original font:
public void SpecialPaste()
{
var helperRichTextBox = new RichTextBox();
helperRichTextBox.Paste();
helperRichTextBox.SelectionStart = 0;
helperRichTextBox.SelectionLength = 1;
Font lastFont = helperRichTextBox.SelectionFont;
int lastFontChange = 0;
for (int i = 0; i < helperRichTextBox.TextLength; ++i)
{
helperRichTextBox.SelectionStart = i;
helperRichTextBox.SelectionLength = 1;
if (!helperRichTextBox.SelectionFont.Equals(lastFont))
{
lastFont = helperRichTextBox.SelectionFont;
helperRichTextBox.SelectionStart = lastFontChange;
helperRichTextBox.SelectionLength = i - lastFontChange;
helperRichTextBox.SelectionFont = new Font(richTextBox1.SelectionFont.FontFamily, richTextBox1.SelectionFont.Size, helperRichTextBox.SelectionFont.Style);
lastFontChange = i;
}
}
helperRichTextBox.SelectionStart = helperRichTextBox.TextLength-1;
helperRichTextBox.SelectionLength = 1;
helperRichTextBox.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, helperRichTextBox.SelectionFont.Style);
richTextBox1.SelectedRtf = helperRichTextBox.Rtf;
}
It's pretty ugly code and I am sure it can be improved and cleaned. But it does what it should.
Clearly this won't work the way you want it if the RTF on the clipboard contains a fragment with a /font directive. Which is very likely. Filtering the RTF fragment is only practical by pasting into a helper RichTextBox. Use the SelectionFont property then copy it back to the clipboard and Paste(). Or do it directly:
int oldpos = richTextBox1.SelectionStart;
richTextBox1.SelectionLength = 0;
richTextBox1.Paste();
int newpos = richTextBox1.SelectionStart;
richTextBox1.SelectionStart = oldpos;
richTextBox1.SelectionLength = newpos - oldpos;
richTextBox1.SelectionFont = richTextBox1.Font;
richTextBox1.SelectionStart = newpos;
I know this is a bit late, but I ran into the same problem and here is my solution (hopefully this will help others):
First, handle the KeyDown event for the RichTextBox:
this.richTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.RichTextBoxKeyDown);
Next, check for paste key event and re-set the clipboard text (this is where the magic happens):
private void RichTextBoxKeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
try
{
Clipboard.SetText(Clipboard.GetText());
}
catch (Exception)
{
}
}
}
Explanation:
I'll start by saying that this was only tested with .NET 4.0. Assuming that none of the functions being used were altered, this will also work with older versions of .NET.
Calling Clipboard.GetText() returns the content in a plain text format (excluding RTF tags). Then we alter the text that's going to be pasted by calling Clipboard.SetText() with the plain text we fetched from Clipboard.GetText(). Now, when the event is done and is passed to the control, it will perform the paste fetching the latest text from the clipboard (our altered version). The reason it is wrapped in a try/catch block is because SetText sometimes throws an exception even though it successfully copied the text to the clipboard. You can of course use the other methods provided by Clipboard to get/set the text, this is just a basic version of the solution.
The newly pasted text will inherit the format of the cursor position, similar to manually typing into the RTB.
Unfortunately this will remove the style of the text as well (bold, coloring, etc)
Hope this helps!
Old I know; Daniel's answer works for me, but only if I replace any instance of richTextBox1.Selection and simply make references to the font and size of the entire richTextBox1. In this case, any RTF I paste will inherit the fontfamily and fontsize currently being used by richTextBox1, while preserving and RTF styling.
public void SpecialPaste()
{
var helperRichTextBox = new RichTextBox();
helperRichTextBox.Paste();
helperRichTextBox.SelectionStart = 0;
helperRichTextBox.SelectionLength = 1;
Font lastFont = helperRichTextBox.SelectionFont;
int lastFontChange = 0;
for (int i = 0; i < helperRichTextBox.TextLength; ++i)
{
helperRichTextBox.SelectionStart = i;
helperRichTextBox.SelectionLength = 1;
if (!helperRichTextBox.SelectionFont.Equals(lastFont))
{
lastFont = helperRichTextBox.SelectionFont;
helperRichTextBox.SelectionStart = lastFontChange;
helperRichTextBox.SelectionLength = i - lastFontChange;
helperRichTextBox.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, helperRichTextBox.SelectionFont.Style);
lastFontChange = i;
}
}
helperRichTextBox.SelectionStart = helperRichTextBox.TextLength-1;
helperRichTextBox.SelectionLength = 1;
helperRichTextBox.SelectionFont = new Font(richTextBox1.Font.FontFamily, richTextBox1.Font.Size, helperRichTextBox.SelectionFont.Style);
richTextBox1.Rtf = helperRichTextBox.Rtf;
}
I've tried to copy text from a word document and pasted it to a RichTextBox in runtime. Everything works fine. I did not adjust anything specific. Just dropped the RichTextBox onto a form and copied the formatted text from the MS Word document.

Categories

Resources