0

I have a WinForm that a user can select some options and then click a button. The button reads the users options from the screen and determines which DB connection string to use. I want to pass the connection string and an empty DataTable to a backgroundworker in a different class. The background worker will then connect to the db, retrieve the data and return the datatable to be bound to a datagrid on the main form.

I've got everything working with the exception of being able to pass the DataTable.

So, my question is there a way to pass two different data types to a BGW? Or is it possible to wrap the string and datatable into a single object?

Gwen
  • 23
  • 1
  • 7
  • `Is it possible to wrap the string and DataTable into a single object?` Sure. You know how to create a class, right? – mason Oct 15 '19 at 16:58

1 Answers1

1

Is it possible to wrap the string and datatable into a single object?

If you need to pass two objects as a single object, you make a class and... wait, we have Tuple. Just create a tuple with two items of the types you need and pass that.

You can use System.Tuple, more precisely System.Tuple<T1, T2>, which is a class with two generic properties Item1 and Item2.

Tuple:

var tuple = Tuple.Create(connectionString, dataTable);

Using System.ValueTuple, or more precisely System.ValueTuple<T1, T2> which is a struct with two generic fields Item1 and Item2, will also work (although it would be boxed).

ValueTuple:

var tuple = (connectionString, dataTable);

See also Named and unnamed tuples.


is there a way to pass two different data types to a BGW

The event handler to DoWork is not limited to the object you pass in RunWorkerAsync. It could read fields of the type where it is declared. Or, if it is a lambda expression, it can also use local variables from the context (see What are 'closures' in .NET?).

Theraot
  • 31,890
  • 5
  • 57
  • 86