Button to import file contents doesn't work

Consider the following line of code:

Button["Browse", Import[SystemDialogInput["FileOpen"]], Method -> "Queued"]

This make a button labeled as “Browse” that calls for the Import function to open a file.

The "Queued" is needed as described here.

I tried it but no output is produced. Why?

On the other hand, executing just this line of code does import the file content:

Import[SystemDialogInput["FileOpen"]]

So, how do I make my button to output the file content?

Thanks a lot!
[1]: https://mathematica.stackexchange.com/a/103430/62632

How about

Button["Browse", content = Import[SystemDialogInput["FileOpen"]], Method -> "Queued"]

content is set to whatever was imported. You should handle the case when the user cancels the dialog and it returns $Canceled.

@Rohit Namjoshi thanks a lot!

Well, if the user cancels the browse dialog, this is equivalent to the statement

Import[$Canceled]

Can you think of a way so that my program doesn’t return that error when the user cancels the dialog?
The only thing I can come up with now is a Switch statement:

If the user completes the Import, than get the values of content. (Assuming that a text string is to be imported)

If, on the other way, the user cancels the dialog, than print the error "You canceled the dialog":

Button["Browse", 
 Switch[content = Import[SystemDialogInput["FileOpen"]],
  Head[content] == String, content, Import[$Canceled], 
  "You canceled the dialog"], Method -> "Queued"]

But this rather produces two errors of the kind

Import: First argument $Canceled is not a valid file, directory, or URL specification.

and besides that the value assigned to content is now $Failed.

Any idea on how to elaborate this?

I am trying to build a sort of a (graphical) user interface inside Mathematica, and that’s why this question arises.

Hi Ehud,

Might be better to check it in a separate function

checkedImport[file_] := If[file === $Canceled, Null, Import[file]]

Button["Browse", content = checkedImport[SystemDialogInput["FileOpen"]], 
 Method -> "Queued"]

If content === Null then the import was cancelled. (Throw/Catch is usually better than a Null check especially if the Null has to be passed/checked up the call stack). You will have to decide how to deal with it in your GUI.