簡體   English   中英

c# - 讀取richtextbox中的特定行

[英]c# - Read a specific line in a richtextbox

所以我在這里有這個代碼

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);
}

如果您不熟悉,那就是查找特定於行的文本。

我想采用那行文字並閱讀整行。

例如,如果該行是someText hfdshjslkgjhsdilg

然后我會得到一個消息框說someText hfdshjslkgjhsdilg

這是LINQ解決方案:

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

要使用RichTextBox方法來執行此操作,可以使用richTextBox1.Lines.ElementAt來獲取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);
}

Lines將返回RichTextBox行, int line告訴您要獲取的行的索引。 因此,您只需使用它們通過使用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);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM