c# richtextbox only shows one line - c#

been searching the internet for some time now and cant find a solution to my problem.
I'm trying to parse some lines into the richtextbox, but i only get one line instead of all of them. Heres a part of my code
foreach (var val in lineCountDict)
{
richTextBox2.Text = (val.Key + " - " + val.Value + " Drops -" +
((double)val.Value / (double)mobDeathCounter) * 100 + " % chance\n");
}
So when i run this i only get one line, any advice would be awesome
Thank you!

Of course you get one line since in each iteration you set richTextBox2.Text to the new value which replaces the old value.
Use richTextBox2.Text+="..."

Related

String randomly containing a newline C#

I'm completely lost with what is happening here.
string send = "!points add " + entries[winner] + " " + prize.ToString();
What I want to send is "!points add winnername prizeamount" but what I get is "!points add winnername\nprizeamount". I put \n because it writes a new line but trying to replace "\n", "\r" and "\t" with " " does nothing.
enter image description here
all I need is the message to be exactly"!points space add space winnername space prizeamount space"
If it's important the entries in my code is a List of strings
The entries strings already contain the new line character(s).
I suggest you replace with Environment.NewLine:
Replace Line Breaks in a String C#
The string object, 'entries[winner]' is having line-feeds (LF) or carriage-returns (CR). You try this to remove all LFs and CRs,
string send = "!points add "
+ entries[winner].Replace("\r", string.Empty).Replace("\n", string.Empty)
+ " " + prize.ToString();
Alternatively, you can use Trim() to remove leading\ trailing LFs\ CRs.
string send = "!points add "
+ entries[winner].Trim()
+ " " + prize.ToString();
No repro. The following code doesn't assert.
var entries=new List<string>{"Aaa", "Bbb", "Ccc"};
int prize=90;
int winner=1;
var send=String.Format("!points add {0} {1}",entries[winner],prize);
var send2="!points add " + entries[winner] + " " + prize.ToString();
Trace.Assert("!points add Aaa 90"==send);
Trace.Assert(send2==send);
If the result contains newlines, it's because the entries values contain newlines.
The best solution would be to clean the input data before storing it in the list, eg with String.TrimEnd or String.Trim, When loading data from a file for example, you can't be sure it doesn't contain trailing spaces.
To read clean data from a file you could use :
var entries=File.ReadLines()
.Select(line=>line.Trim())
.ToList();
If you add the entries one by one from user input :
entries.Add(newEntry.Trim());
If you can't change how the data is read (why?) you can trim when whenever you use an entry value:
var send=String.Format("!points add {0} {1}",entries[winner].Trim(),prize);
Loading clean data is a lot easier

Why Wont This Code Snip Something From A String

So I have data which has data separated by ", ". I am trying to separate the different data using Substring.
input = input.Substring(input.IndexOf(", ") + 2, input.Length - input.IndexOf(", ") + 2);
In this scenario, I have already read the first piece of data and I am trying to cut it off. In order to do this, I take the index of the first instance of ", " and add 2 to it, which gives me the end index of the phrase. Then I take the length of the entire string and subtract the last index of the first ", ". This gives me the length from the end of ", " to the end of the string. This is what I want to snip. For some reason, I keep getting an ArgumentOutOfRange exception when this piece of code runs. If someone could tell me what I am doing wrong, it would be very helpful.
Then I take the length of the entire string and subtract the last
index of the first ", ".
Not so - you forgot parenthesis around input.IndexOf(", ") + 2. Your intention was to do this:
input = input.Substring(
input.IndexOf(", ") + 2,
input.Length - (input.IndexOf(", ") + 2)); // < note additional "()"
If you were not trying to put everything into one line - you could have avoided this problem:
var idx = input.IndexOf(", ") + 2;
input = input.Substring(idx, input.Length - idx);
You can also use Remove to achieve the same result:
input = input.Remove(0, input.IndexOf(", ") + 2);

save listView content to a file

I'm trying to save the contents of my listView.
But I'm having some issues with it. In my text file it will look like this:
ListViewItem: {1234};ListViewSubItem: {daily};ListViewSubItem: {Backup};ListViewSubItem: {Every 2 days at: 23:0};ListViewSubItem: {};ListViewSubItem: {}
But I don't like that it adds "ListViewItem:" and "ListViewSubItem:" etc with my data.. I just want those strings inside {}.
And here is my code:
FileStream file = new FileStream(dataFolder + "\\BukkitGUI\\schedule.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
sw.Close();
file.Close();
Any help on this?
EDIT: Image of my listView:
Your code does this:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(listItem + ";" + listItem.SubItems[1] + ";" + listItem.SubItems[2] + ";" + listItem.SubItems[3] + ";" + listItem.SubItems[4] + ";" + listItem.SubItems[5]);
}
This is doing the following:
foreach (ListViewItem listItem in listView1.Items)
{
string listItemString = listItem.ToString();
// etc.
}
What do you think the value of listItem.ToString() will be?
The default implementation of object.ToString() simply outputs the name of the type. The implementation for ListViewItem and ListViewSubItem apparently output the name of the type, plus the content of the item or subitem.
If you want something different output, then you need to do it yourself. Output listItem.Text and listItem.SubItems[n].Text instead.
Q: If your input data is in JSON format, perhaps your best bet is to get a JSON parser?
For example:
Parsing REST Services JSON Responses (C#): illustrates System.Runtime.Serialization.Json
Otherwise, if it's just a "funny format", look at the .Net TextFieldParser:
Parsing Text Files with the TextFieldParser Object
It's too long to post it as comment so I'll write an answer. I hope at least it will give you a good direction on one way to deal with it. In general you need some way to manipulate string. Many options comes to mind, but in your case I think that using regex or regular expressions is the best option since they are powerful, you have a clear criteria about what should go inside the .txt file and what not, and you work with relatively small amount of data so even though the regular expressions are considered slower than other options, in your case I think this won't be a problem.
Here is what I've tried - just created a static method (some sort of helper method) that will clean the string for you so that you get only the info you need. The method itself is :
public static string ParseListView(string ListViewText)
{
var regex = new System.Text.RegularExpressions.Regex("{.*?}");
var match = regex.Match(ListViewText);
return match.ToString().TrimStart('{').TrimEnd('}');
}
Pretty simple method. There's a lot of things that you can adjust if needed to work better for your case. For example I'm using regex.Match() which returns only the first match, but maybe you'll find regex.Matches() more suitable for you. There are also a lot of other options when you work with regular expressions in C# so be sure to check them out.
Then in you foreach loop you just:
foreach (ListViewItem listItem in listView1.Items)
{
sw.WriteLine(ParseListView(listItem) + ";" + ParseListView(listItem.SubItems[1]) + ";" + ParseListView(listItem.SubItems[2]) + ";" + ParseListView(listItem.SubItems[3]) + ";" + ParseListView(listItem.SubItems[4]) + ";" + ParseListView(listItem.SubItems[5]));
}
Of course this looks pretty ugly so the logic inside the foreach loop most probably can be improved but I think this will get you going.

adding space in texbox results when sending thru email

wassup guys im new to C# coding and i did a search but couldn't find exactly what im looking for. So i have a couple of text-boxes which holds string elements and integers
what i want to do is when these boxes are filled in i want to send a summary of the email to client/customer but the format is whats getting me.
(first, one) are strings equaling different text-boxes
my code is:
emailCompseTask.Body = first + one + Enviroment.NewLine +
second + two + Enviroment.NewLine
and so on problem is which i send thru email it shows something like this:
computer service25.00
instead of:
computer service 25.00
is there a way to add spacing to make this more presentable? or even a better way perhaps thanks in advance guys
try this :
emailCompseTask.Body = first + one + " "+ second + two ;
body takes as HTML input, check here for more spacing option.
I'm a bit confused, but you just want to add some spacing in the output? Just throw some spaces in there like you would another variable.
first + " " + one + Environment.NewLine
+ second + " " + two + Environment.NewLine;
You can use a table
string tableRow = #"<tr>
<td>{0}</td>
<td>{1}</td>
</tr>";
string htmlTable = #"<table>
{0}
</table>";
string rows = "";
// Can do this in a loop
rows += string.Format(tableRow, first, one);
rows += string.Format(tableRow, first, one);
emailComseTask.Body = string.Format(htmlTable, rows);

c# write message to textbox

Kind of new to c# GUI stuff
I am trying to output a message, a number to a textbox.
1 Button will calculate the number, then I want to write a message like " Number has been seen: "
I tried
Form2.resultBox.Text.Write("Number one has been seen: ", num0);
that doesn't work.
Also tried
Form2.resultBox += Console.WriteLine("Numer one has been seen: ", num0);
Im going to have about 16 of these messages
ideas?
Form2.resultBox.Text = "Number one has been seen: " + num0;
To set the value of a TextBox, you should set a value on the Text property like so:
resultBox.Text = "Number one has been seen: " + num;
how about using the string.Format
Form2.resultBox.Text = string.Format("Number one has been seen: {0}", num0);
eliminates having to use + sign

Categories

Resources