< character in RichTextBox causing issues - c#

EDIT - Sorry folks, i guess i wanted to "obscure" my work code too much... i don't know why it got so many downvotes but anyway. see below for update/edit with actual code.
I am trying to insert a piece of text into an existing section of a line (<data) which resides at the beginning of a line in my RichTextBox control. However, whenever i do that in the following manner:
private void AddSelectedIntellisense(object sender, EventArgs e)
{
ToolStripItem x = sender as ToolStripItem;
int cursorpos = this.txt_Body.SelectionStart;
string final = this.txt_Body.Text.Insert(cursorpos, x.Text);
//final var at breakpoint is equal to "<data log=\"Original\""
//then i assign it/that to the RTB.Text
this.txt_Body.Text = final;
//when checked with breakpoint, this.txt_Body.Text is equal to
//"log=\"\"<data log=\"Original\""
this.txt_Body.SelectionStart = cursorpos + x.Text.Length;
}
I am thinking that it is the < character that is causing issues when i assign the string to the .Text property (because if i replace the < with a [ in my logic, no problems), but i don't know how to fix it... if you could help me i would really appreciate it.
I also checked all of the indexes manually and they all lign up perfectly... so i don't know why the RTB.Text value is different than the string but if someone knows please tell me.
Cheers!

You are first setting:
txt = this.RTB1.Text.Substring(starts, length);
Then on the next line you are replacing the value of txt:
txt = this.RTB1.Text.Insert(index,"log='test'></data>");
You are probably looking to concatenate the strings:
string txt = this.RTB1.Text.Substring(starts, length);
txt += this.RTB1.Text.Insert(index,"log='test'></data>");
this.RTB1.Text = txt;

Ok folks... i suppose i'll give it to Aaron, since it's like somewhat related and nobody else answered.
The answer was:
I am using the RTB.On_TextChanged event to fire off the intellisense based on a condition. However, because i am also setting text the RTB.Text value within the Intellisense, the condition became true twice and added the specific text twice. So i setup a flag when i add intellisense text and check it in the on_textchanged event.
Cheers and sorry for the confusion.

Related

How to display a specific line at the top of a RichTextBox

I'm pulling the content from a text file into a RichTextBox. I've got the RichTextBox set up to where it only shows 6 lines at a time. I've got a search method that finds the text I need within the RichTextBox, but what I am needing it to do is display 6 specific lines. Each "item" in my text file consists of 6 lines. No matter which of the six lines the search method finds the text on, I need the RichTextBox to only display the 6 lines of each "item" with the currently selected "found" text remaining highlighted.
I've gotten it working reasonably well thanks to a few code examples I've pull from this site. But every now and then, it doesn't work entirely well, and am looking for some advice from a fresh set of eyes looking at my code and perhaps even be told an easier/more efficient way to go about it. But here is my code so far. Thanks in advance!
try
{
string s = txtFindPlaylistEntry.Text;
rtxEditPlaylistEntry.Focus();
findPosEntry = rtxEditPlaylistEntry.Find(s, findPosEntry, RichTextBoxFinds.None);
// Jump to the line we need.
int count = rtxEditPlaylistEntry.GetLineFromCharIndex(findPosEntry);
count = (count - (count % 6)) + 1; // Must be divisible by 6 then plus 1
rtxEditPlaylistEntry.SelectionStart = rtxEditPlaylistEntry.Find(rtxEditPlaylistEntry.Lines[count]);
rtxEditPlaylistEntry.ScrollToCaret();
rtxEditPlaylistEntry.Select(findPosEntry, s.Length);
findPosEntry += txtFindPlaylistEntry.Text.Length;
}
catch
{
MessageBox.Show("No occurences found");
findPosEntry = 0;
}
As of right now, I'm attempting to use a line count with modulus plus 1 to get the line I need. Like I said, it works, just not 100% of the time and I can't figure out why.
EDIT to try to accommodate Minimal, Complete, Verifiable.
I've already posted my "find" function. Here is other related code that might be useful. First, here is my code for creating the various controls I am using.
rtxEditPlaylistEntry = new RichTextBox();
rtxEditPlaylistEntry.Location = new System.Drawing.Point(15, 90);
rtxEditPlaylistEntry.Size = new System.Drawing.Size(375, 85);
rtxEditPlaylistEntry.Multiline = true;
rtxEditPlaylistEntry.ScrollBars = RichTextBoxScrollBars.None;
Here is my button function to pull text from a file and place it into the RichTextBox.
private void btnBrowseForPlaylistToEditEntry_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "LPL Files|*.lpl";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
savedFileNameEntry = openFileDialog.SafeFileName;
txtPathToPlaylistToEditEntry.Text = openFileDialog.FileName;
}
// After finding the file, load it into the richtextbox control
using (StreamReader sr = File.OpenText(openFileDialog.FileName))
{
// Initially show the first 6 lines (IE first entry). This should be accomplished by
// the richtextbox control settings
rtxEditPlaylistEntry.Text = sr.ReadToEnd();
}
previousNextCount = 0;
}
I hope this is sufficient. If not please let me know!

How do I replace a part of a line in a text file with user input?

Here's the code.
private void SaveButton_Click(object sender, EventArgs e)
{
string textBoxText = TextBox.Text;
var lines = File.ReadAllLines(#"F:\Bioshock2SP.ini");
foreach(string line in lines)
{
if (line.Contains("VoVolume="))
{
//This is where I get confused.
string settingLine = line;
string replaceline = (line.Replace(line, textBoxText));
File.WriteAllText(#"F:\Bioshock2SP.ini", settingLine);
}
break;
}
MessageBox.Show("Setting saved!");
}
The idea is to replace part of a setting in a Settings.ini file for a game I play, using the user input of a textbox in my form. The user types in a number for example, "1.56" and then hit the Save button to replace the existing line with their input. In this case that setting is the volume.
The application runs completely fine, but after hitting save and going into the settings file my input isn't saved.
There should be a change in the way you save the file.
Save each line of the file as you get it, editing if required.
void SaveButton_Click(object sender, EventArgs e)
{
var textBoxText = TextBox.Text;
var lines = File.ReadAllLines(#"F:\Bioshock2SP.ini");
using (var file = new StreamWriter(#"F:\Bioshock2SP.ini"))
foreach(string line in lines)
{
if (line.Contains("VoVolume="))
file.WriteLine(line.Substring(0, 9) + textBoxText); // Writes something like 'VoVolume=1.56'
else file.WriteLine(line); // No editing required
}
MessageBox.Show("Setting saved!");
}
I think there are a couple of separate issues with your code:
Replace Function
string replaceline = (line.Replace(line, textBoxText));
Replace accepts a string to look for and a string to replace it with. Your first argument is 'line', so it would replace the whole line with the value in textBoxText. I assume you only want to replace a portion of the line with that value. In that case, you need to use something like line.Replace(searchString, textBoxText) where you have previously defined searchString as the text you want to replace. If you don't know what that value is, but there is a pattern, you might want to look into using regular expressions which will let you define a pattern to search and replace.
WriteAllText Function
File.WriteAllText(#"F:\Bioshock2SP.ini", settingLine);
This line will replace the entire contents of BioShock2SP.ini with the value in settingLine. There are two problems here.
One is that settingLine was the saved value before you did the replacement - so it has not included the results of your replace operation. You should use replaceline (assuming it has been correctly modified).
Even if you do that, though, the other is that File.WriteAllText will replace the whole file with the value in settingLine - which is probably not what you want. You'd be better off modifying the line in the array and using File.WriteAllLines to re-output the whole array - assuming the file has multiple lines in it.
The hints above may help you resolve this - to properly answer the question though, I'd need to see a sample of what the file looks like, and the patterns you are trying to replace.

Get caret position in RichTextBox_Click event

I'm working on a text editor which includes a RichTextBox. One of the features that I want to implement is to show in a TextBox the current Line and Column of the caret of the forementioned RichTextBox at any moment.
Here's part of the code that I use (the rest of my code has nothing to do with my issue):
int selectionStart = richTextBox.SelectionStart;
int lineFromCharIndex = richTextBox.GetLineFromCharIndex(selectionStart);
int charIndexFromLine = richTextBox.GetFirstCharIndexFromLine(lineFromCharIndex);
currentLine = richTextBox.GetLineFromCharIndex(selectionStart) + 1;
currentCol = richTextBox.SelectionStart - charIndexFromLine + 1;
At this point, I should mention that when someone is using a RichTextBox, there are three ways that the caret can change location:
By changing the Text of the RichTextBox
By using the arrow keys on the keyboard
By clicking anywhere on the RichTextBox
The code that I posted above works with no issues in the first two cases. However, it doesn't really work in the third case.
I tried using the Click event and I noticed that the selectionStart variable would always get the value of 0, which means that I always get the same and wrong results. Moreover, using the same code on other events like MouseClick and MouseUp did not solve my problem since selectionStart is 0 even in the duration of these events.
So, how can I get the current Line and column everytime the user clicks on the RichTextBox?
You want something like:
private void richTextBox1_MouseUp(object sender, MouseEventArgs e)
{
RichTextBox box = (RichTextBox)sender;
Point mouseLocation = new Point(e.X, e.Y);
box.SelectionStart = box.GetCharIndexFromPosition(mouseLocation);
box.SelectionLength = 0;
int selectionStart = richTextBox.SelectionStart;
int lineFromCharIndex = box.GetLineFromCharIndex(selectionStart);
int charIndexFromLine = box.GetFirstCharIndexFromLine(lineFromCharIndex);
currentLine = box.GetLineFromCharIndex(selectionStart) + 1;
currentCol = box.SelectionStart - charIndexFromLine + 1;
}
It seems to me that what you really want is to handle the TextBoxBase.SelectionChanged event. Then any action that causes the selection to change will invoke your code, and as an added benefit the current selection will have been updated by the time your event handler is called, and you'll be assured of getting correct values.
If that does not address your specific need, then I must not be understanding the question. In that case, please provide a good, minimal, complete code example that shows clearly what you're trying to do, with a precise description of what that code does and how that's different from what you want it to do.

display a string in textbox

I want to get the data from my serial port and display this data in a textbox. but when i run mu code it displays just one line in the textbox and it gets replaced by the next. but I want the each part of the string under the next one.
private void button1_Click(object sender, EventArgs e)
{
SerialPort serP = new System.IO.Ports.SerialPort("COM3", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);
while (true)
{
serP.Open();
serP.WriteLine("test");
string dataIn = serP.ReadLine();
textBox1.Text = dataIn;
serP.Close();
}
}
this is my code, I hope some one can help me out with this.
Rick
Just concatenate your text:
textBox1.Text += dataIn + Environment.NewLine;
And make sure your textbox is multiline (textBox1.Multiline = true for standart Windows.Forms.TextBox or somethimg similar if it's textbox from some controls library)
I would go with Andy Korneyev's answer. But if you want each part in a new line you could alter his code like below,
textBox1.Text += dataIn + Environment.NewLine;
Also if you want to set the textbox as MultiLine in code behind,
textBox1.TextMode = TextBoxMode.MultiLine;
Note:
I assume you are working with WinForms. If so, you can also use RichTextBox control. It doesn't need to be set has MultiLine.
I agree with Pavan. If you want to use more than one line i would prefer RichtTextBox, too.
Also if you only want to display something, you could use a simple label, too.
I think thats much nicer for a user than to have it in a TextBox, but only if you want to display something without using it in other things.

C# Text box remaining empty

I'm calling a public method from another class. It takes in a List as a parameter, and goes through the list printing out each item into a text field. The problem is the text field is remaining empty!. I've checked that the list is populated by outputing the item to the console before I put it into the text box, and the text is coming up fine there.
The list contains strings, and should output each string to the textfield followed by a semi colon.
This is the method which is being called:
public void fillAttachment(List<string> attachList)
{
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
txtAttach.Text += attachList[i] + ";";
}
}
I would solve it in this way:
foreach(var attach in attachList)
{
Console.WriteLine(attach);
txtAttach.AppendText(string.Format("{0};", attach));
}
Setting the text property on a text box and it not displaying could be one of the following:
You are not looking at the same control as you are setting the text in
Could you have instantiated a second copy of the form object and it is this form that you are setting the txtAttach text property in?
Could the control that you are expecting to be populated be a different one? Right click the text box that you want the text to appear in click properties and check the name.
Something else is clearing the textbox after you set it
Right click the txtAttach.Text and click Find All References, this will show you all the places that the Text property is referenced - written and read - in your project. This is a very useful way to locate other interaction with this control.
Fomatting is making the text box appear empty
Is the Font too small, or in the same colour as the background. Can you select the text in the text box?
The easiest way to test all of the above is to create a new text control on your form with a different name, change your code to populate it, check that it is indeed populated, then replace the old one.
As an aside, you could also reduce the code with a single line as follows:
public void fillAttachment(List<string> attachList)
{
txtAttach.Text = String.Join(";", attachList.ToArray());
}
Although this obviously skips out the console write line function.
Not sure why yours doesn't work but I would have done it like this...
public void fillAttachment(List<string> attachList)
{
string result = "";
//OR (if you want to append to existing textbox data)
//string result = txtAttach.Text;
for (int i = 0; i < attachList.Count; i++)
{
Console.WriteLine("List: " + attachList[i]);
result += attachList[i] + ";";
}
txtAttach.Text = result;
}
Does that work for you? If not then there is something else very wrong that is not obvious from your code

Categories