2012-05-21 49 views
3

我有2個按鈕,當我點擊這些按鈕時我讀取了不同的文件。由於文件很大,所以我使用MsgBox來顯示讀取文件,所以我想在richTextBox中顯示它。按鈕點擊打開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; 
} 

有沒有其他方法可以做到這一點?

+0

所以,你要顯示一個消息框一個RichTextBox,對不對? –

+0

創建新的窗體,並把它只有RichTextBox,也許關閉按鈕,然後顯示它在按鈕單擊 –

+0

@ Krishanu Dey:是的,如果它是一個大文件,那麼我想滾動... – linguini

回答

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(); 
} 
+0

它看起來不錯,有沒有辦法在'title'中調用選定的文件名並增加字體? – linguini

+0

當然,您必須使用'Path.GetFileNameWithoutExtension(fileName)'方法來獲取文件的名稱並將其作爲標題傳遞。要增加字體大小,你必須設置一個像這樣的新字體:'rtbMessage.Font = new System.Drawing.Font(「Microsoft Sans Serif」,20f);' – cansik

+0

Genial,'rtbMessage.Font = new Font(「Arial 「,10,FontStyle.Bold);'Merci – linguini