流阅读器无法将文本从文件文本获取到文本框

3
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);
}

我确定文件名是正确的,但运行程序时它显示了一个空文本框。

结果如下图所示: enter image description here

2个回答

2
如其他地方所述,实际问题源于展示对话框在执行对话框之前阻塞。
这里有几个要点:
  1. 为什么不创建一个专用的表单,即MyDeciatedShowAllForm,而不是动态创建它?
  2. 如果您正在使用实现了IDisposable的内容,则最好使用using语句。
示例
using(var r = new StreamReader("empData.txt"))
{
    string strShowAllData = r.ReadToEnd();                
    txtShowAll.Text = strShowAllData;
}
  1. 为什么不使用File.ReadAllText,这样可以节省一些可打印字符。

示例

string strShowAllData = File.ReadAllText(path);
  1. 您可能需要将文本框设置为多行

示例

// Set the Multiline property to true.
textBox1.Multiline = true;
// Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical;
// Allow the RETURN key to be entered in the TextBox control.
textBox1.AcceptsReturn = true;
// Allow the TAB key to be entered in the TextBox control.
textBox1.AcceptsTab = true;
// Set WordWrap to true to allow text to wrap to the next line.
textBox1.WordWrap = true;
// Show all data
textBox1.Text = strShowAllData;
  1. 为什么不先使用File.Exists检查文件是否存在?

示例

if(!File.Exists("someFile.txt"))
{
    MessageBox.Show(!"oh nos!!!!! the file doesn't exist");
    return;
}
  1. 最后,这是你需要记住的一点:你需要学会如何使用调试器和断点,通过调试器浏览代码。我的意思是,如果你在txtShowAll.Text = strShowAllData;上设置了一个断点,你就应该知道文本文件中是否有文本,这样你就不会对此产生任何疑虑了。

2

我刚刚注意到你在以对话框模式显示表单后向文本框添加文本。为什么不像下面代码中我所做的那样,将frmShow.ShowDialog();移动到try块的末尾,并确保empData.txt存在于其路径中。

        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);
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接