我有这段代码,但它没有用。我尝试了几个不同的版本,但没有任何工作。我是新手,仍然不明白一切。
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);
}
}
}
我认为这个编辑器需要很多纯文本。
答案 0 :(得分:5)
在对ShowDialog()的调用返回后,您正在添加事件处理程序。将它移到之前它可能会起作用。
答案 1 :(得分:2)
根据documentation,单击“打开”或“保存”按钮时会发生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);
}
}
}