简体   繁体   中英

c# - Read a specific line in a richtextbox

So I have this code here

int pos = richTextBox1.Find("someText", RichTextBoxFinds.MatchCase);
if (pos != -1)
{
    int line = richTextBox1.GetLineFromCharIndex(pos);
    string lineString = line.ToString();
    string inside = string.Format(lineString);
    MessageBox.Show(inside);
}

If you are not familiar all it is is finding what line specific text is on.

I want to take that line of text and read what the entire line is.

So for example, if the line is someText hfdshjslkgjhsdilg

then I would get a messagebox saying someText hfdshjslkgjhsdilg

Here is LINQ solution:

string line = richTextBox.Lines.FirstOrDefault(l => l.Contains(searchedText));
if (line != null) MessageBox.Show(line);

To make use of RichTextBox methods to do that, you could use richTextBox1.Lines.ElementAt to get your Text :

int pos = richTextBox1.Find("someText", RichTextBoxFinds.MatchCase);
if (pos != -1) {
    int line = richTextBox1.GetLineFromCharIndex(pos);
    string lineString = richTextBox1.Lines.ElementAt(line);
    MessageBox.Show(lineString);
}

The Lines will return you lines in the RichTextBox and your int line will tell you the index of the line you want to grab. So, you simply need to use them to grab your line by using Lines.ElementAt(line)

int pos = richTextBox1.Find("someText", RichTextBoxFinds.MatchCase);
if (pos != -1)
{
    int line = richTextBox1.GetLineFromCharIndex(pos);
    int nextLineStart = richTextBox1.GetFirstCharIndexFromLine(line + 1);
    if (nextLine != -1)
    {
        string lineString = richTextBox1.Text.Substring(pos, nextLineStart - pos);
        MessageBox.Show(lineString);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM