3

我有 2 个按钮,单击这些按钮时会读取不同的文件。由于文件很大,我使用 来显示 readfile MsgBox ,所以我想将它显示在richTextBox.

当我单击这些按钮中的任何一个时,如何打开richTextBox并显示?read file

private void button1_Click(object sender, EventArgs e)
{  
    DisplayFile(FileSelected);//DisplayFile is the path of the file
    var ReadFile = XDocument.Load(FileSelected); //Read the selected file to display

    MessageBox.Show("The Selected" + " " + FileSelected + " " + "File Contains :" + "\n " + "\n " + ReadFile);
    button1.Enabled = false;
}

private void button2_Click(object sender, EventArgs e)
{
    FileInfo file = (FileInfo)comboBox2.SelectedItem;
    StreamReader FileRead = new StreamReader(file.FullName);
    string FileBuffer = FileRead.ReadToEnd(); //Read the selected file to display

    //MessageBox.Show("The Selected" + " " + file + " " +"File Contains :"  + "\n " + "\n " + FileBuffer);
    // richTextBox1.AppendText("The Selected" + " " + file + " " + "File Contains :" + "\n " + "\n " + FileBuffer);
    //richTextBox1.Text = FileBuffer;
}

还有其他方法吗?

4

1 回答 1

3

这是一个简单的示例(基于代码的表单设计)。如果您通过 GUI 设计器创建表单会更好:

private void button1_Click(object sender, EventArgs e)
{
    //test call of the rtBox
    ShowRichMessageBox("Test", File.ReadAllText("test.txt"));
}

/// <summary>
/// Shows a Rich Text Message Box
/// </summary>
/// <param name="title">Title of the box</param>
/// <param name="message">Message of the box</param>
private void ShowRichMessageBox(string title, string message)
{
    RichTextBox rtbMessage = new RichTextBox();
    rtbMessage.Text = message;
    rtbMessage.Dock = DockStyle.Fill;
    rtbMessage.ReadOnly = true;
    rtbMessage.BorderStyle = BorderStyle.None;

    Form RichMessageBox = new Form();
    RichMessageBox.Text = title;
    RichMessageBox.StartPosition = FormStartPosition.CenterScreen;

    RichMessageBox.Controls.Add(rtbMessage);
    RichMessageBox.ShowDialog();
}
于 2012-05-21T09:02:14.907 回答