1

我有这个代码,但它不工作。我尝试了几个不同的版本,但没有任何效果。我是一个新手,仍然不明白一切。

    OpenFileDialog filedialog = new OpenFileDialog();

    private void button3_Click(object sender, EventArgs e)
    {

        filedialog.ShowDialog();
        filedialog.FileOk += filedialog_FileOk;
    }

    void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
    {
        using (StreamReader myStream = new StreamReader(filedialog.FileName))
        {
            string line;
            // Read and display lines from the file until the end of  
            // the file is reached. 
            while ((line = myStream.ReadLine()) != null)
            {
                listBox1.Items.Add(line);
            }
        }
    }

我认为这个编辑器需要大量纯文本。

4

2 回答 2

5

在对 ShowDialog() 的调用返回,您将添加事件处理程序。将其移至之前,它可能会起作用。

于 2013-10-04T15:35:36.140 回答
2

根据文档,单击打开或保存按钮时会发生 FileOK 事件。您正在单击内附加事件处理程序。您可能希望在页面加载时或点击发生之前的某个地方执行此操作。

例如:

OpenFileDialog filedialog = new OpenFileDialog();
protected void Page_Load(object sender, EventArgs e)
{
    filedialog.FileOk += filedialog_FileOk;
}
private void button3_Click(object sender, EventArgs e)
{
    filedialog.ShowDialog();        
}
void filedialog_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
    using (StreamReader myStream = new StreamReader(filedialog.FileName))
    {
        string line;
        // Read and display lines from the file until the end of  
        // the file is reached. 
        while ((line = myStream.ReadLine()) != null)
        {
            listBox1.Items.Add(line);
        }
    }
}
于 2013-10-04T15:36:30.730 回答