Replace '\n' in multiple textbox at once - c#

I have a window form application, inside this application, there have several textbox and want to replace the breakline and send out as email in one click. Since i have multiple textbox, instead of writing like this:
string text = textBox1.Text;
text = text.Replace("\n", "<br/>");
string text2 = textBox2.Text;
text2 = text2.Replace("\n", "<br/>");
...
string textBody ="<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text + "</td></tr>" +"<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>" + ...
is there any ways to replace the line in these textbox in one time?
I try to put in a loop:
for (int i = 1; i < 20; i++)
{TextBox txtbox = (TextBox)this.Controls.Find("textBox" + i, true)[0]; }
I stuck at here. Any suggestion?

Your Form is a Control, which has a property Controls This property "Gets the collection of controls contained within the control".
You can use Enumerable.OfType to filter this so you get only the TextBoxes.
Is there any ways to replace the line in these textbox in one time?
You'll need a foreach to replace the text:
var textBoxesToUpdate = this.Controls.OfType<TextBox>();
foreach (TextBox textBox in textBoxesToUpdate)
{
string proposedText = textBox.Text.Replace("\n", "<br/>");
textBox.Text = proposedText;
}
I also see this in your question
string textBody = "<tr bgcolor = '#C39BD3'><td>Name</td><td>" + text1 + "</td></tr>"
+ "<tr bgcolor = '#C39BD3'><td>Age</td><td>" + text2 + "</td></tr>"
+ ...
I don't know what you want with this. Consider to edit the question and change this.

Related

Fill Line with hyphens

i'm trying to fill one line of my label with hyphens. Here's what i got right now. what is the function that i can use to fill the next line without manually typing out all the hyphens?
lblResumé.Text = intNbrTotTut.ToString() + str1erePhrase + Environment.NewLine
string myString = "Test" + Environment.NewLine + "Test2" +Environment.NewLine;
label1.Text = myString.Replace(System.Environment.NewLine, "_");

Is there a way to change the color of a specific word/string at run time of a WPF ListBox Item?

So all i want is if a specific word will be added in a listbox row/item, at run time, cause i am using a timer to add items at run time from my Database, i want that specific word/string to have a diferent color.
ie: All new item added that contains the string/word "Aproved", should be colored as green as soon as a new item its added to the WPF ListBox at run time.
private void dispatcherTimerMensagem_Tick(object sender, EventArgs e)
{
if (!(principalDB.testarConexãoDB()))
{
dispatcherTimerVendasFechadas.Stop();
dispatcherTimerMensagem.Stop();
LstMensagem.ItemsSource = null;
LbPbVendasFechadas.ItemsSource = null;
}
else
{
mensagem = principalDB.selectMessagemUsuario(null);
if (mensagem != string.Empty)
{
this.Activate();
LstMensagem.Opacity = 1;
LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);
voice.Voice = voice.GetVoices().Item(0);
myWorkerMensagem.WorkerReportsProgress = true;
myWorkerMensagem.WorkerSupportsCancellation = true;
myWorkerMensagem.RunWorkerAsync();
if (VisualTreeHelper.GetChildrenCount(LstMensagem) > 0)
{
Border border = (Border)VisualTreeHelper.GetChild(LstMensagem, 0);
ScrollViewer scrollViewer = (ScrollViewer)VisualTreeHelper.GetChild(border, 0);
scrollViewer.ScrollToBottom();
}
}
else
{
LstMensagem.Opacity = 0.5;
}
}
}
So the LstMensagem will recieve a new item at run time, from the variables declared, in this line of code:
LstMensagem.Items.Add(principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem);
If a specific word/string comes up, as ie "aproved" i want that string with a different text color,as example, brushed in green.
Use a TextBlock instead string. For entire item:
var text = principalDB.mensagemRemetente + " (" + principalDB.mensagemData + ")" + ": " + mensagem;
var tb = new TextBlock();
tb.Text = text;
if(text.Contains("aproved"))
tb.Foreground = Brushes.Green;
LstMensagem.Items.Add(tb);
For only part of the item, use the Inlines property to add different formatted texts:
var tb = new TextBlock();
tb.Inlines.Add(new Run { Foreground = Brushes.Green, Text =
principalDB.mensagemRemetente});
tb.Inlines.Add(" (" + principalDB.mensagemData + ")" + ": " + mensagem);
LstMensagem.Items.Add(tb);

Can make the color separately?

As you can see it is all red. I need the number to be red, but text to be black as shown on picture below. This is my code :
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
str1 = str;
str1 += listBox2.Text;
wassaw.Text = str1;
TextBox1.ForeColor = Color.Red;
switch (str1)
{
case "Привет1" :
TextBox1.Text = "" + Environment.NewLine + "1. привет " + Environment.NewLine + "2. привет " + Environment.NewLine + "3. привет ";
break;
case "Привет2" :
TextBox1.Text = "" + Environment.NewLine + "1. привет ";
break;
case "Приветф3" :
TextBox1.Text = "" + Environment.NewLine + "1 привет ";
break;
case "Приветы4" :
TextBox1.Text = "" + Environment.NewLine + "1 привет ";
break;
}
}
Not using a regular TextBox. The TextBox control just allows single color, single formatting text.
There are several options. You could create your own control, use external libraries, or you can use the RichTextBox which does allow formatting and coloring. With a little help, you can achieve what you want:
See this question how to do that: Color different parts of a RichTextBox string.
Another option would be to use a grid control, like the TableLayoutPanel and put the numbers and text in separate labels.

RichTextBox not printing newline

I have this method that replaces(in bold) some words in a string and show the changed string in a ritchtextBox.
In the final string I need to replace the # symbol by a newline.
I already tried checked this forum tying several solutions, but nothing worked.
The method I use is
private string bold(string ing)
{
StringBuilder builder = new StringBuilder();
ing = " " + ing + " ";
builder.Append(#"{\rtf1\ansi");
foreach (string word in splitwords)
{
var regex = new Regex(#"(?<![\w])" + word + #"(?![\w])", RegexOptions.IgnoreCase);
ing = regex.Replace(ing, m => #"\b" + m.ToString() + #"\c0");
}
ing = ing.Replace(#"\b", #"\b ");
ing = ing.Replace(#"\c0", #" \b0");
ing = ing.Replace("#", Environment.NewLine);
builder.Append(ing);
builder.Append(#"}");
MessageBox.Show("builder.ToString():" + builder.ToString());
return builder.ToString();
}
When I call the this method and "put it" in the ritchTextBox it doesn´t print the new line
ingred.Rtf = bold(ingd);
How should I solve this??
EDIT:: input string - line1 # line2 # line3
output in the MessageBox
Builder.ToString() : {\rtf1\ansi\b line1\b0
line2
line3
}
output in the ritchTextBox: line1 line2 line3
Instead of
ing = ing.Replace("#", Environment.NewLine);
Try
ing = ing.Replace("#", #"\par\r\n");
Use This Code For Repalce
int startIndex = 0, index;
RichTextBox myRtb = new RichTextBox(); // if have A richtextBox Remove thisline and Use your Richtextbox
myRtb.Rtf = STRRTF;// if have A richtextBox Remove thisline and Use your Richtextbox
while ((index = myRtb.Text.IndexOf("#", startIndex)) != -1)
{
myRtb.Select(index, word.Length);
myRtb.SelectedText ="\n";
startIndex = index + 1;
}
Better use Environment.NewLine for adding new line also Make sure yourRTB.MultiLine property is set to true. assign string to richtext box like this yourRTB.AppendText(t)
Try replacing it with a "\r\n" character sequence?
edit: is MultiLine property of ritchtextBox enabled?

Click item in listbox and View details in multiline textbox

I would like to click on an item in a listbox and display the attributes that were passed into that listbox to a multiline textbox.
Below is the code I have written on form initialisation
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
foreach (KeyValuePair<int, Individual> kvp in ReadFromFile.individuals)
{
listBox2.Items.Add("ID = " + kvp.Value.id + " Name = " + kvp.Value.name.givenName + " " + kvp.Value.name.surname + " DoB = " + kvp.Value.birth.date);
}
int testIndividual = 94;
string genderOut = "";
if (ReadFromFile.individuals[testIndividual].gender == "M")
{
genderOut = "MALE";
}
else if (ReadFromFile.individuals[testIndividual].gender == "F")
{
genderOut = "FEMALE";
}
try
{
textBox1.AppendText(
"Name = " + ReadFromFile.individuals[testIndividual].name.givenName + " "
+ ReadFromFile.individuals[testIndividual].name.surname
+ Environment.NewLine + "Gender = " + genderOut
+ Environment.NewLine + "Birth date = " + ReadFromFile.individuals[testIndividual].birth.date
+ Environment.NewLine + "Birth place = " + ReadFromFile.individuals[testIndividual].birth.place
+ Environment.NewLine + "Death date = " + ReadFromFile.individuals[testIndividual].death.date
+ Environment.NewLine + "Death place = " + ReadFromFile.individuals[testIndividual].death.place);
}
catch
{
MessageBox.Show("This individual doesnt exist");
}
}
}
I would like to add more so I can click on a listbox item and the details for that item will be shown in the textbox
I get the feeling I may have to override the ToString() method or regex it. Im still quite a novice programmer so go easy on me :) THANK YOU
You need to handle the SelectedIndexChanged event for your listbox.
One way to do this is to bring up Form1.cs[Design] and select the listbox. In the property grid (Alt+Enter) click the icon that looks like this:
Find the event SelectedIndexChanged and double click it. That will hook up an event handler for you in the auto generated Form1.cs.designer file.
Next, replace the code for your Form1 class with the following:
public partial class Form1 : Form
{
private Dictionary<int, Individual> _individuals;
public Form1()
{
InitializeComponent();
ReadFromFile.Read("sample.GED");
_individuals = ReadFromFile.individuals;
listBox1.DataSource = _individuals.Select(individual => individual.Value).ToList();
listBox1.DisplayMember = "name";
listBox1.ValueMember = "id";
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
textBox1.Clear();
var individual = listBox1.SelectedItem as Individual;
string genderOut = (individual.Gender == "M") ? "MALE" : "FEMALE";
var displayText
= String.Format("Name = {0} {1}\r\n" +
"Gender = {2}\r\n" +
"Birth date = {3}\r\n" +
"Birth place = {4}\r\n" +
"Death date = {5}\r\n" +
"Death place = {6}"
, individual.name.givenName
, individual.name.surname
, genderOut
, individual.birth.date
, individual.birth.place
, individual.death.date
, individual.death.place);
textBox1.AppendText(displayText);
}
}
A few notes about some of the things i've changed.
I've moved the code that was setting the textbox value into the SelectedIndexChanged event handler
I've refactored that code so that it's more readable by using the static String.Format method (all those Environment.NewLine repeats you had were messy).
I've setup the data for the list box using the DataSource property instead of your foreach loop.
Also, one thing you'll notice with this is that the list items in the listbox will not show the correct text. This is because you appear to be using some custom classes or structs for the name, birth and death of an Individual? To fix this, you need to add a new property to the Individual class like this:
public class Individual
{
// ... your code
public string DisplayName
{
get { return String.Format("{0} {1}), name.givenName, name.surname; }
}
// ... the rest of your code
}
Then you will need to change the line in my code above that looks like this:
listBox1.DisplayMember = "name";
to this:
listBox1.DisplayMember = "DisplayName";
Final note: You should probably be using "Upper Camel Case" for your property names. That means that they start with an upper case letter and then the first letter of each word is also upper case. For example, name.givenName should be Name.GivenName. This is a widely used convention.

Categories

Resources