按钮单击打开richTextBox并显示readfile

时间:2012-05-21 08:28:37

标签: c# winforms visual-studio-2010

我有2个按钮,当我点击这些按钮时,我会读取不同的文件。我使用MsgBox来显示readfile,因为文件很大,所以我想在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;
}

还有其他办法吗?

1 个答案:

答案 0 :(得分: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();
}