Reputation: 1
I would like to ask for everyone's help . what would I wanna do is to close a random loaded window whenever I press a .button
on the Main Window
. Here is where I am as of today the window name are ( im1,im2,im3,im4)
. As expected all of the window will be opened upon loading, but somewhere on my code is wrong that when I pressed the button non of the open window would be closed. Also I would like to have a non-repeating
random code. so if i clicked the button once again it would be a 100% sure that it would not try to close the already closed window. Hope You Understand My English I am sorry.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Random g = new Random();
int ans = g.Next(1, 5);
if (ans == 1)
{
im1 v1 = new im1();
v1.Close();
}
if (ans == 2)
{
im2 v2 = new im2();
v2.Close();
}
if (ans == 3)
{
im3 v3 = new im3();
v3.Close();
}
if (ans == 4)
{
im4 v4 = new im4();
v4.Close();
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
im4 v4 = new im4();
v4.Show();
im3 v3 = new im3();
v3.Show();
im2 v2 = new im2();
v2.Show();
im1 v1 = new im1();
v1.Show();
}
}
}
Upvotes: 0
Views: 48
Reputation: 184
Fields are instance members, they are variables which can be accessed from every method of the class.
As M.kazem Akhgary suggested, your code would look like this:
public partial class MainWindow : Window
{
im1 v1 = null;
im2 v2 = null;
im3 v3 = null;
im4 v4 = null;
public MainWindow()
{
InitializeComponent();
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
Random g = new Random();
int ans = g.Next(1, 5);
if (ans == 1)
{
v1.Close();
}
if (ans == 2)
{
v2.Close();
}
if (ans == 3)
{
v3.Close();
}
if (ans == 4)
{
v4.Close();
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
v4 = new im4();
v4.Show();
v3 = new im3();
v3.Show();
v2 = new im2();
v2.Show();
v1 = new im1();
v1.Show();
}
}
Upvotes: 1