I have a RichtTextBox in my C# application that shows a log to the user. The problem is that newly inserted text appends below the old text, but I want to append it on top of the old text.
For example, When I append the text "Newtext" it looks like this:
RichtTextBox:
|---------------------
|Oldtext |
|Newtext |
|---------------------
But it needs to look like this:
RichTextBox:
|---------------------
|Newtext |
|Oldtext |
|---------------------
This is the code I'm using for filling my RichTextBox:
public void DisplayLog(string logtext)
{
if (logtext != "")
{
if (this.txtLog.InvokeRequired && !txtLog.IsDisposed)
{
Invoke(new MethodInvoker(delegate()
{
txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
}));
}
else if (!txtLog.IsDisposed)
{
txtLog.AppendText(DateTime.UtcNow + ": " + logtext + "\n");
}
}
}
Can somebody help me out please?
Answer:
Inserting at top of richtextbox
Use Insert
txtLog.Text = txtLog.Text.Insert(0,DateTime.UtcNow + ": " + logtext + "\n");
I think txtlog is the RichTextBox and you should prepend this.
To do this go at start using
txtlog .SelectionStart = 0;
txtlog .SelectionLength = 0;
txtlog .SelectedText = (DateTime.UtcNow + ": " + logtext + "\n");
Related
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + txtFirstName.Text[0] + txtMiddle.Text + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
I'm trying to get 1 character white space inbetween cboTitle.Text, txtFirname.Text, txtMiddle.Text, and txtLastName, but they all output the information together, but I want them spaced evenly. what do I need to do? thanks in advance.
I'm going to post some other code thats below the one above in my project, just in case it might be relevant.
string AssembleText(string Title, string FirstName, string MiddleInitial, string LastName, string AddressLines, string City )
{
string Result = "";
Result += Title + " ";
Result += FirstName.Substring(0, 2) + " ";
// Only append middle initial if it is entered
if (MiddleInitial != "")
{
Result += MiddleInitial + " ";
}
Result += LastName + "\r\n";
// Only append items from the multiline address box
// if they are entered
if ( AddressLines != "")
{
Result += AddressLines + "\r\n";
}
//if (AddressLines.Length > 0 && AddressLines.ToString() != "")
//{
// Result += AddressLines + "\r\n";
//}
Result += City;
return Result;
}
}
}
If you just want a space between those specific fields in btnAssemble_Click, you can just insert them like this:
string myStr = foo + " " + bar + " " + baz;
So your first function would be modified to read:
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " + txtMiddle.Text + " " + txtLastName.Text + "\r\n" + txtStreet.Text + "\r\n" + cboCity.Text);
}
A few other comments:
It's not clear to me what the AssembleText() function you posted has to do with this. I am confused though, as I see a few lines appending spaces at the end just like I mentioned above.
Using the String.Format() function may make this code easier to read and maintain.
Using Environment.NewLine instead of "\r\n" will make the string contain the newline character defined for that specific environment.
Using a StringBuilder object may be faster over concatenation when building strings inside of a loop (which may not apply here).
Using String.format() should feet the bill. It also make your code easy to read.
txt.assembled.text = String.Format("{0} {1} {2} {3}",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text
);
It would be like this
private void btnAssemble_Click(object sender, EventArgs e)
{
txtAssembled.Text = (cboTitle.Text + " " + txtFirstName.Text[0] + " " +txtMiddle.Text + " " + txtLastName.Text + "\r\n" +txtStreet.Text + "\r\n"+ cboCity.Text);
}
It seems that you want String.Join; whenever you want to combine strings with a delimiter, say, " " (space) all you need is to put
String combined = String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text);
Complete implementation (joining by space and new line) could be
txtAssembled.Text = String.Join(Environment.NewLine,
String.Join(" ",
cboTitle.Text,
txtFirstName.Text[0],
txtMiddle.Text,
txtLastName.Text),
txtStreet.Text,
cboCity.Text);
I'am exporting some data to a .txt file as follows:
String content;
String path=#"e:\coding\";
String name="test.txt";
path+=name;
System.IO.File.Delete(path);
for (i=0;i<row-1;i++)
{
try
{
if (r[i].points.Count() > 2)
{
content = "Route " + (i + 1).ToString() +" Truck_id:"+trk[i].truck_name.ToString()+ " Max_load="+trk[i].capacity.ToString()+ "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
System.IO.File.AppendAllText(path, "Points Load Reached_AT Max_load" + Environment.NewLine);
System.IO.File.AppendAllText(path, "========================================" + Environment.NewLine);
for (int j = 0; j < (r[i].points.Count()); j++)
{
content = r[i].points[j].ToString() + " " + c[r[i].points[j]].load.ToString() +" "+ r[i].time_list[j].ToString()+" "+c[r[i].points[j]].max_load.ToString()+"\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine);
}
content = "Total " + r[i].ld.ToString() + "\n";
System.IO.File.AppendAllText(path, content + Environment.NewLine );
content = "Route Complete: " + r[i].reach_at.ToString();
System.IO.File.AppendAllText(path, content + Environment.NewLine+Environment.NewLine);
}
}
catch (IndexOutOfRangeException e)
{
break;
}
}
As expected the output I get is not properly formatted:
The spaces are causing the text to be jumbled and not arranged. My reputation does'nt allow me to post a screenshot but I guess It can be understood what is happening.
Is there way so that the text is properly formatted neatly column wise without looking jumbled.
If you need a text, you can use tabs:
System.IO.File.AppendAllText(path, "Points\t\tLoad\t\tReached_AT\t\tMax_load" + Environment.NewLine);
// ...
content = r[i].points[j].ToString() + "\t\t " + c[r[i].points[j]].load.ToString() +"\t\t"+ r[i].time_list[j].ToString()+"\t\t"+c[r[i].points[j]].max_load.ToString()+"\n";
Just play with amount of tabs (\t for one, \t\t for two, etc...). Hope it can help.
Another solution would be to use commas:
System.IO.File.AppendAllText(path, "Points,Load,Reached_AT,Max_load" + Environment.NewLine);
and save to CSV-file (comma-separated values). Then you can import the data to Microsoft Excel or to other software.
You can find bunch full of good information on how to format the string contents in the The format item MSDN but for quick answer, an example for your string
content = "Route " + (i + 1).ToString() + " Truck_id:" + trk[i].truck_name.ToString() + " Max_load=" + trk[i].capacity.ToString() + "\n";
If we assume,
i maximum 10 digits,
Truck_name max 45 characters
capacity max 10 digits
content = String.Format("{0,-20}{1,55}{2,20} " + Environment.NewLine, "Route " + (i + 1).ToString(), " Truck_id:" + trk[i].truck_name.ToString(), " Max_load=" + trk[i].capacity.ToString());
I have a textbox1 that lets the user input a text, a button that adds the text to textbox2.
this is my code but it doesnt create a new line when I add another text.
string date = DateTime.Now.ToString();
txt_details.Text = date + " " + txt_summary.Text.ToString() + Environment.NewLine + Environment.NewLine ;
Notice the += operator.
txt_details.Text += "\n" + date + " " + txt_summary.Text.ToString();
Looks like you should be appending (use +=); instead you are overwriting.
string date = DateTime.Now.ToString();
txt_details.Text += date + " " + txt_summary.Text.ToString() + Environment.NewLine + Environment.NewLine
Make sure Multiline is enabled.
Ensure that TextBox.Multiline property is set to true
txt_details.Multiline = true;
I have Created a small XML tool, to find the numbers of element present in Multiple XML files.
This code gives the fine result for the elements which are must in XML files.
But when it comes to specific elements, which may be present or not in XML files, Software give me result as:
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P565-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P566-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMF0-004D-P567-00000-00.xml
Instance: 0
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P001-00000-00.xml
**Instance: 11**
10/8/2012 11:27:51 AM
C:\Documents and Settings\AlaspuMK\Desktop\KS\success\4CPK-PMG0-004D-P002-00000-00.xml
Instance: 0
Now here the problem is XML files may be 500-1000 when i search the tag which may be present or not the tool gives me result for each and every files. In this case specific tag present instance may be 0 or multiple.
Can any one suggest the changes in my Code to find the file name in which instance is greater than 0. and if instance > 0 print it in text box.
My current code:
public void SearchMultipleTags()
{
if (txtSearchTag.Text != "")
{
try
{
//string str = null;
//XmlNodeList nodelist;
string folderPath = textBox2.Text;
DirectoryInfo di = new DirectoryInfo(folderPath);
FileInfo[] rgFiles = di.GetFiles("*.xml");
foreach (FileInfo fi in rgFiles)
{
int i = 0;
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(fi.FullName);
//rtbox2.Text = fi.FullName.ToString();
foreach (XmlNode node in xmldoc.GetElementsByTagName(txtSearchTag.Text))
{
i = i + 1;
//
}
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
//rtbox2.Text += fi.FullName + "instances: " + str.ToString();
}
}
catch (Exception ex)
{
MessageBox.Show("Invalid Path or Empty File name field.");
}
}
else
{
MessageBox.Show("Dont leave field blanks.");
}
}
If I understand correctly, you want to display text only if the i is greater than 0?
if(i > 0 )
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
Use
if(i > 0)
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
instead of simple
rtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";
You could always just use this code inside the try block:
rtbox2.Text =
String.Join(Environment.NewLine + Environment.NewLine,
from fi in (new DirectoryInfo(textBox2.Text)).GetFiles("*.xml")
let xd = XDocument.Load(fi.FullName)
let i = xd.Descendants(txtSearchTag.Text).Count()
where i > 0
select String.Join(Environment.NewLine, new []
{
DateTime.Now.ToString(),
fi.FullName,
i.ToString(),
}));
Does it all in one line (bar the formatting). :-)
I wrote this function
private void richAdd(string who, string what)
{
string colorstring = who + " ( " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " ) :";
richTextBox1.Text += colorstring + " " + what + "\r\n\r\n";
richTextBox1.DeselectAll();
richTextBox1.Select(richTextBox1.Find(colorstring), colorstring.Length);
richTextBox1.SelectionColor = Color.Blue;
richTextBox1.DeselectAll();
}
which is supposed to color who+time in blue and what in black.
Yet after the second time it makes all the text blue... any ideas what could be wrong with it?
Thanks!
try
private void richAdd(string who, string what)
{
string colorstring = who + " ( " + DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " ) :";
richTextBox1.AppendText(colorstring + " " + what + "\r\n\r\n");
richTextBox1.Select(richTextBox1.Text.LastIndexOf(colorstring), colorstring.Length);
richTextBox1.SelectionColor = Color.Blue;
}