我使用OpenFileDialog()
上传文件,因此我可以阅读.csv文件并将其添加到数据网格中。但是,如果在未选择文件的情况下关闭OpenFileDialog
,则会崩溃。所以我将它放在try { } catch { }
块中作为临时修复。
有人可以为未被选中的文件提供更好的解决方案吗?
修改 这是我的OpenFileDialog代码:
// ... Code to Setup OFD here ...
// If the search for the file is OK (i.e. the file exists), stores the filename in a string.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
fileName = openFileDialog1.FileName;
Console.WriteLine(fileName);
}
// Runs the Populate Data Grid View method.
UploadFromExternalSource();
这是AddtoDataGrid代码:
// Try/catch used if a file was not uploaded.
try
{
// Reads the text and splits the text into rows by each new line.
importFile = File.ReadAllText(CView.fileName).Split('\n');
foreach (string line in importFile)
{
// Splits each line into indiviual columns each time it comes in contact with a comma (",")
// then increments the line count (determined by the new line) by 1.
data = line.Split(',');
CView.dataGridView1.Rows.Add(data);
lineCount++;
}
}
catch (Exception e) { Console.WriteLine(e.Message); }
答案 0 :(得分:3)
OpenFileDialog.ShowDialog()
将返回DialogResult
。如果用户选择了文件,您可以检查DialogResult.OK
。
示例:
var opf = new OpenFileDialog();
if(opf.ShowDialog() == DialogResult.OK)
{
//do something
}