将字符串从一个目标设置为另一个目标

时间:2015-06-13 09:23:49

标签: c#

我想在第二个richtextbox中包含字符串"oldSummary",但是在打开文件后,所有摘要的功能都属于streamRead。有没有办法在单击btn1按钮时显示oldSummary字符串?目前它是空白的,因为它的全局字符串设置为""但我希望它显示oldSummary按钮中设置的mnuOpen字符串。

string oldSummary = "";
private void mnuOpen_Click(object sender, EventArgs e)
{

    //Load up file code which I remove for this example but goes here…

    //Add data from text file to rich text box
    richTextBox1.LoadFile(Chosen_File, RichTextBoxStreamType.PlainText);

    //Read lines of text in text file                
    string textLine = "";
    int lineCount = 0;

    System.IO.StreamReader txtReader;
    txtReader = new System.IO.StreamReader(Chosen_File);

    do
    {
        textLine = textLine + txtReader.ReadLine() + " ";
        lineCount++;
    }
    //Read line until there is no more characters
    while (txtReader.Peek() != -1);

    //seperate certain characters in order to find words
    char[] seperator = (" " + nl).ToCharArray();

    //number of words, characters and include extra line breaks variable
    int numberOfWords = textLine.Split(seperator, StringSplitOptions.RemoveEmptyEntries).Length;

    int numberOfChar = textLine.Length - lineCount;

    string divider = "------------------------";

    //Unprocessed Summary
    string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

    txtReader.Close();
}

private void btn1_Click(object sender, EventArgs e)
{
    string wholeText = "";
    string copyText = richTextBox1.Text;
    wholeText = oldSummary + copyText;
    richTextBox2.Text = wholeText;
}

2 个答案:

答案 0 :(得分:1)

如果你想使用全局变量oldSummary,那么不要在菜单打开事件处理程序中重新声明一个具有相同名称的变量,只需使用全局变量

//Unprocessed Summary
oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

答案 1 :(得分:0)

尝试更换:

string oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

使用:

oldSummary = "Word Count: " + numberOfWords + "Characters Count: " + numberOfChar + divider;

以便将值分配给btn1_Click中使用的类字段。