I have made a small application that should download files from a website. I have a btn called btnDownload_Click
. When it is clicked, a BackgroundWorker
is created in order to keep the form
functioning for the user while running the program. It then calls the void Downloadfiles(object sender, DoWorkEventArgs e)
in order to download the file, with a bunch of settings specified in a struct
called DownloadSettings
.
The code for btnDownload_Click
is shown below:
private void btnDownload_Click(object sender, EventArgs e)
{
//settings from the user (mostly)
DownloadSettings settings = new DownloadSettings();
settings.cond = txtSearchTerm.Text;
settings.count = Int32.Parse(txtNumberofStudies.Text);
settings.outputpath = txtFilePath.Text;
settings.fmt = cmbFormats.Text;
settings.flds = 10000;
if (settings.outputpath == "")
{
MessageBox.Show("Please select an output directory.", "Output directory needed");
}
else
{
//https://stuff.seans.com/2009/05/21/net-basics-do-work-in-background-thread-to-keep-gui-responsive/
SetAppState(AppStates.DownloadingFile);
// Set up background worker object & hook up handlers
_worker = new BackgroundWorker();
_worker.DoWork += new DoWorkEventHandler(Downloadfiles);
_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);
_worker.WorkerReportsProgress = true;
_worker.WorkerSupportsCancellation = true;
_worker.ProgressChanged += new ProgressChangedEventHandler(bgWorker_ProgressChanged);
// Launch background thread to do the work of reading the file. This will
// trigger BackgroundWorker.DoWork(). Note that we pass the filename to
// process as a parameter.
_worker.RunWorkerAsync(settings);
}
}
My problem is that I cannot use settings
as an argument in Downloadfiles
:
private void Downloadfiles(object sender, DoWorkEventArgs e) //string cond, string fmt, string outputpath
{
DownloadSettings settings = e.Argument as DownloadSettings;
}
I just get the error The as operator must be used with a reference type or nullable type ('DownloadSettings' is a non-nullable value type)
. How can I solve this? I got the idea for this solution from: https://stackoverflow.com/a/29011429/7502962