Search code examples
c#filestream

Stream reader cannot get the text from file text to a textbox


try
{
    Form frmShow = new Form();
    TextBox txtShowAll = new TextBox();
    frmShow.StartPosition = FormStartPosition.CenterScreen;
    frmShow.Font = this.Font;
    frmShow.Size = this.Size;
    frmShow.Icon = this.Icon;
    frmShow.Text = "All data";
    txtShowAll.Dock = DockStyle.Fill;
    txtShowAll.Multiline = true;
    frmShow.Controls.Add(txtShowAll);
    frmShow.ShowDialog();

    StreamReader r = new StreamReader("empData.txt");
    string strShowAllData = r.ReadToEnd();                
    txtShowAll.Text = strShowAllData;
    r.Close();
}
catch (Exception x)
{
     MessageBox.Show(x.Message);
}

I sure that is the file name is correct when I run the program it shows an empty text box.

The result enter image description here


Solution

  • I just noticed you are adding text to the textbox after showing the form in dialog mode. Why don't you move the frmShow.ShowDialog(); to the end of the try block just like I have done it in the code below, and make sure the empData.txt exists at its path.

            try
            {
                Form frmShow = new Form();
                TextBox txtShowAll = new TextBox();
                frmShow.StartPosition = FormStartPosition.CenterScreen;
                frmShow.Font = this.Font;
                frmShow.Size = this.Size;
                frmShow.Icon = this.Icon;
                frmShow.Text = "All data";
                txtShowAll.Dock = DockStyle.Fill;
                txtShowAll.Multiline = true;
                frmShow.Controls.Add(txtShowAll);
    
                StreamReader r = new StreamReader("empData.txt");
                string strShowAllData = r.ReadToEnd();
                txtShowAll.Text = strShowAllData;
                r.Close();
    
                frmShow.ShowDialog();
            }
            catch (Exception x)
            {
                MessageBox.Show(x.Message);
            }