Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF using statement to open another form

Tags:

c#

winforms

wpf

I wrote a C# app in Winforms and am now rewriting it in WPF. In the Winforms version I used the following to open another window while sending it information and receive information back from it:

using (showSelection showSelection1 = new showSelection(listBox2.SelectedItem.ToString()))
            {
                showSelection1.ShowDialog();               
                storage1.showID = showSelection1.showID;
                storage1.numOfSeasons = showSelection1.numOfSeasons;

            }

This worked fine, I sent the selected item from listBox2 and received showID and numOfSeasons using this code in the showSelection form:

this.showID = Convert.ToInt32(dataGridView1[2, dataGridView1.CurrentCell.RowIndex].Value);
this.numOfSeasons = dataGridView1[1, dataGridView1.CurrentCell.RowIndex].Value.ToString();
this.Close();

Now, in the WPF version I try the same thing:

using (ShowSelection showSelection = new ShowSelection(showListBox.SelectedItem.ToString()))
            {

            }

But inside the using( ) I get this error: ShowSelection: type used in a using statement must be implicitly convertible to 'System.IDisposable'

I'm not really sure where to do from here. Can I fix this and still go about it the same way or is there a different way I should be doing this? The ShowSelection window is just a datagrid with a single button.

like image 793
Jrow Avatar asked Nov 01 '25 16:11

Jrow


2 Answers

WPF components don't use Win32 handles (Window does, but it self-manages), so they have no need to be IDisposable, and you have no need to Dispose them or use them in a using block.

Once there are no more references to your Window it'll be marked for collection by the GC, same as other pure NET components.

In case you want to use it within a using block, you can implement IDisposable on your window manually, but it's indeed not needed.

In case you want to manually remove resources (and keep using it in a using block), then the simplest you can do:

public class ShowSelection : Window, IDisposable
{
    public void Dispose()
    {
      /* here you'd remove any references you don't need */
    }
}

But unless there's a need for it, I'd advise against doing so

like image 91
Jcl Avatar answered Nov 04 '25 05:11

Jcl


it's simply says that ShowSelection class do not derive from IDisposable so use it without the using:

ShowSelection showSelection = new ShowSelection(showListBox.SelectedItem.ToString());

and than access the properties you need to: showSelection.#####

like image 38
Oscar Avatar answered Nov 04 '25 05:11

Oscar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!