質問

I have a file upload using an OpenFileDialog(), so I can read .csv files and add the to a datagrid. However, if the OpenFileDialog is closed without a file selected, it crashes. so I placed it in a try { } catch { } block as a temporary fix.

Can someone provide a better solution to a file not being selected?

EDIT Here is my OpenFileDialog Code:

// ... 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();

Here is the AddtoDataGrid code:

// 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); }
役に立ちましたか?

解決

The OpenFileDialog.ShowDialog() will return DialogResult. You can check for DialogResult.OK if the user selected the file.

Example:

var opf = new OpenFileDialog();

if(opf.ShowDialog() == DialogResult.OK)
{
//do something
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top