How can I write on a new Line in a MultiLine Textbox? - c#

I have to make a program, where you're able to type in a minimum value and a maximum value. Then all the numbers from the min. to max. that are even should be showed in a multiline textbox.
But when the even number gets written into the textbox, it always overwrites the number which was written into the textbox before.
I tried Enviroment.NewLine and also this \r\n thing, but I probably used it wrong.
private void cmdstart_Click(object sender, EventArgs e)
{
for (int i = Convert.ToInt32(textBox1.Text); i <= Convert.ToInt32(textBox2.Text); i++)
{
int a = i % 2;
if (a == 0)
{
textBox3.Text = Convert.ToString(i);
}
}
}
In the end, its supposed to output all even numbers from the min. to max. in a multiline textbox. Each number should be on a new line.

It happens because you overwrite it each time.
Try the following code:
textBox3.Text += i.ToString()+Environment.NewLine;

Make sure that you have set Multiline property to true on the textBox3.
You can set it through properties window after selecting textbox3 or you can write below line in the form constructor after initializeComponents is done.
textBox3.Multiline = true;
Once this is done, Environment.NewLine or \r\n both should work.

You can test it by yourself, if you write multiline text
Input:
1
2
3
4
5
6
7
to your textbox using designer and Text property, you can see that it generates something like this:
txt value:
"1\r\n2\r\n3\r\n4\r\n5\r\n6\r\n7"
Code:
string txt = multiLineTextBox.Text;
So if you add \r\n to your existing text, it will append text to new line:
for (int i = Convert.ToInt32(textBox1.Text); i <= Convert.ToInt32(textBox2.Text); i++)
{
int a = i % 2;
if (a == 0)
{
textBox3.Text = $"{textBox3.Text}{i}\r\n";
// or using string.Format for older versions
//textBox3.Text = string.Format("{0}{1}\r\n", textBox3.Text, i);
}
}

Related

Iterate through RichTextBox making specific words bold

I wrote a Vacuum tube Cross reference program.
I can't figure out how to iterate through the RichTextBox1 to make the requested tube value Bold.
Existing output when searching for 6AU8A
Tube Cross1 Cross2 Cross3 Qty Location
6AU8 6AU8A 6BH8 6AW8 2 PM BOX 3
6AU8A 6AU8 6BH8 6AW8 6 BOX 9
6BA8A 6AU8 6AU8A 8AU8A 1 BOX 11
6CX8 6AU8A 6EB8 6GN8 2 BOX 16
6EH5 6AU8A 2081 6AW8A# 1 BOX 19
6GH8 6EA8 6GH8A 6AU8A 2 BOX 23
6GH8A 6GH8 6EA8 6AU8A 10 BOX 22
6GH8A 6GH8 6EA8 6AU8A 5 BOX 23
So, I need any occurrence for search term (6AU8A in this example) in Bold.
Using VS 2019, Windows Application, compiled for .NET 4.8.1, runs on Windows 7 & 10 PC's.
public int FindMyText(string text)
{
length = text.Length;
// Initialize the return value to false by default.
int returnValue = -1;
// Ensure that a search string has been specified and a valid start point.
if (text.Length > 0)
{
// Obtain the location of the first character found in the control
// that matches any of the characters in the char array.
int indexToText = richTextBox1.Find(text);
// Determine whether the text was found in richTextBox1.
if (indexToText >= 0)
{
// Return the location of the character.
returnValue = indexToText;
start = indexToText;
}
}
return returnValue;
}
Once you call Find(), the value will be SELECTED (if it exists). Then you can change the Font to include Bold. The Find() function has a "Start" position, which allows you to find the NEXT occurrence. So you start at 0, then add the length of the search string to get the next starting position. If the value returned is -1, then there were no more matches and you can stop.
Looks something like this:
private void button1_Click(object sender, EventArgs e)
{
BoldText("6AU8A"); // get your input from somewhere...
}
private void BoldText(String value)
{
int startAt = 0;
int indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
while (indexToText != -1)
{
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
startAt = startAt + value.Length;
indexToText = richTextBox1.Find(value, startAt, RichTextBoxFinds.None);
}
}
Here it is in action:
If you actually need to use a RichTextBox for this, you could use a simple Regex to match one or more terms, then use Index and Length properties of each Match to perform the selection and change the Font and/or other styles (in the code here, optionally, the color)
Pass a collection of terms to match (containing one or more terms) to the method:
string[] parts = { "6AU8A", "6GH8" };
Highlight(richTextBox1, parts, FontStyle.Bold);
// also specifying a Color
Highlight(richTextBox1, parts, FontStyle.Bold, Color.Red);
// or deselect previous matches
Highlight(richTextBox1, parts, FontStyle.Regular);
The Regex only matches complete sequences, e.g., passing 6GH8, it won't partially highlight 6GH8A
If you prefer a partial selection, remove both the \b boundaries in the pattern
using System.Text.RegularExpressions;
private void Highlight(RichTextBox rtb, IEnumerable<string> terms, FontStyle style, Color color = default)
{
color = color == default ? rtb.ForeColor : color;
string pattern = $#"\b(?:{string.Join("|", terms)})\b";
var matches = Regex.Matches(rtb.Text, pattern, RegexOptions.IgnoreCase);
using (var font = new Font(rtb.Font, style)) {
foreach (Match m in matches) {
rtb.Select(m.Index, m.Length);
rtb.SelectionColor = color;
rtb.SelectionFont = font;
};
}
}

Spliting numerical input by linebreak in a textbox, doing some math on it, and outputting results in a new textbox

I'm attempting to create a wpf app that takes a list of numerical values, separated by line breaks, in one textbox. You click a button, and it outputs the new numerical values into a second textbox. I'm running into issues separating the values the user inputs.
For this to make more sense the first textbox is called inputBox and the second textbox is called outputBox. The button will have event mathClick. We will have the button just multiply the number by 2.
This is what I have:
private void mathClick(object sender, RoutedEventArgs e)
{
foreach (var num in inputBox.Text.Split("\n"))
{
if(double.TryParse(num, out double value))
{
outputBox.Text = Convert.ToString(value * 2);
}
}
}
This is what happens
inputBox:
7.02
18.98
3.51
outputBox:
7.02
It's only grabbing the last value in the textbox and doing the arithmetic on that.
This is the scenario I'm trying to achieve
inputBox:
7.02
18.98
3.51
outputBox:
14.04
37.96
7.02
Any help is greatly appreciated.
I figured it out, if any other beginners like me come across this - you must remember Textbox will return a string. The way I fixed it was to split the input at the linebreak and store it in a string array
string[] stringNum = textbox.text.split("\n");
Then you can use a for loop to convert this array of type string to a double and print the double to your textbox with a linebreak each time the loop runs.
for (int i = 0; i < stringNum.Length; i++)
{
double num = Convert.ToDouble(stringNum[i]);
textbox.text += Convert.ToString($"{num}\n");
}
Hope this helps someone else, thanks.

I Can't create a new line inside textbox within a for loop

I have been trying to create a new line after each divisor is printed, but it hasn't worked with any of the methods. I changed the multiline attribute of the text box to true and tried \r\n and then the Environment.NewLine but it doesn't work, the number are always printed in one line without spaces.
private void button_MouseClick(object sender, MouseEventArgs e)
{
int divisor, inserted;
inserted = Convert.ToInt32(txt_input.Text);
for (divisor = 1; divisor <= inserted; ++divisor)
{
if (inserted % divisor == 0)
{
txt_output.AppendText(Convert.ToString(divisor).Replace(Environment.NewLine, "<br />"));
}
}
}
txt_output.AppendText(Convert.ToString(divisor).Replace(Environment.NewLine, "<br />"));
??? so try
txt_output.Text = txt_output.Text+Convert.ToString(divisor)+"\r\n";
AppendText adds to the end, which seems like what you want, but thats whats preventing you from going to the next line, also dont think you need to replace, if you want to clear the textbox before setting it again just call:
txt_output.Text="";

What is windows form c# writeline equivalent

I have created an order form that includes a 16 length string array. Depending on the customer selection, I need the info from the array to appear in a text box e.g order summary. I can't figure it out. Here is sample code from one radio button and one check box. If these were selected how do I get the selection to display in a box? Please note I already have the "cost" part of it working correctly.
//Handle CPU Box Radio Btn
if (rdInteli3.Checked)
{
cost += 100.00;
item [0] = "Intel i3";
}
//Handle Hard Drive Check Box
if (ckHardDrive1Tb.Checked)
{
cost += 200.00;
item[11] = "1 TB Hard Drive";
}
I've tried this. Didn't work.
for (int i = 0; i < 16; i++)
{
txtSummary.Text = item[i];
}
Thanks
You'll have a multi-line TextBox control. You can append text to the control by calling its AppendText method. You code would look like this:
txtSummary.Clear();
for (int i = 0; i < 16; i++)
{
txtSummary.AppendText(item[i]);
}
You may wish to include new lines each time you add an item. In that case change the code like so:
txtSummary.AppendText(item[i]);
txtSummary.AppendText(Environment.NewLine);
or perhaps:
txtSummary.AppendText(item[i] + Environment.NewLine);
An alternative form is to use concatenation on the Text property:
txtSummary.Clear();
for (int i = 0; i < 16; i++)
{
txtSummary.Text += item[i] + Environment.NewLine;
}
And yet another option would be to build the text outside the control, for instance using a StringBuilder instance, and then assigning it all to the Text property in one go.
I guess that you want to use MessageBox:
MessageBox.Show("Hello World");
What is windows form c# writeline equivalent
Its the same Console.WriteLine but since there is no console you will see the output in Output window.
I need the info from the array to appear in a text box
You need to build a string , better if you use StringBuilder. Append your data there and then assign the result to your TextBox.Text property.
If your data is in array item then , its better if you use string.Join like:
txtSummary.Text = string.Join(Environment.NewLine, item);
If you want to use StringBuilder then you can do:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < item.Length; i++)
{
sb.Append(item[i]);
}
txtSummary.Text = sb.ToString();
Using string builder, how do I had space between the selection and
maybe a comma?
You can do:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < item.Length; i++)
{
sb.Append(item[i]);
sb.Append(" ,");
}
txtSummary.Text = sb.ToString().Trim(',',' ');
Or better
txtSummary.Text = string.Join(" ,", item);
You can use StringBuilder or String.Format to build a complete string that you want to show to the user. String.Format uses similar semantics as WriteLine.
Then assign this string to a MessageBox, a label or a textfield on your form or whereever you want it.
You can use that:
using System.Diagnostics;
Debud.WriteLine("This is test string");
You can check the result at the Output Window

How to set max byte length of datagridview when paste

I have a datagridview where DataNames can be entered in a textbox column.I restrict the input length of this column to 6 characters by using the MaxInputLength property of the DataGridViewTextBoxColumn.
Here, I want to explain my problem step by step.
1. I wrote Double Byte Characters(eg.1234567890) on a notepad and copy it.Then I went to this DataGridViewTextBox ,Right Click and then choosed Paste.The DataGridViewTextBox showed 123456.
2.I wrote Double Byte Characters(eg.123456) on a notepad and copy it.Then I went to this DataGridViewTextBox ,Right Click and then choosed Paste.The DataGridViewTextBox showed 123456.
So,MaxInputLength property only restrict to the input character length( not caring single byte or double byte).
I want to show only 123(6 bytes).Is there a property or a way to restrict the byte character length especially in Paste operation?
Thanks in advance.
I guess you could just handle it in the TextChangedEvent
Something like:
private void textBox1_TextChanged(object sender, EventArgs e)
{
var textBytes = Encoding.UTF8.GetBytes(textBox1.Text);
var textByteCount = Encoding.UTF8.GetByteCount(textBox1.Text);
var textCharCount = Encoding.UTF8.GetCharCount(textBytes);
if (textCharCount != textByteCount && textByteCount >= 12)
{
textBox1.Text = Encoding.UTF32.GetString(Encoding.UTF32.GetBytes(textBox1.Text), 0, 12);
}
else if (textBox1.Text.Length >= 6)
{
textBox1.Text = textBox1.Text.Substring(0, 6);
}
}

Categories

Resources