Quote:
in form1, i wrote Form2 sd = new Form2(); sd.ShowDialog();
i want to open a serial port by combo box selection. in combo box, i have some of serial ports as "com1, com2, ..., com8". when i select one of these serial ports in form1, this "comx" opens in form2 by serialport1.open();
Now that we (finally) have an idea of what you want to do ... we can proceed.
The first task is to analyze whether we are in a scenario that requires
notification or
access: in this case we know that when Form2 'sd is shown, modally, that it needs to "know" which ComboBox Item was selected in Form1.
We also know that since Form2 is shown modally, the user cannot switch back to Form1 while Form2 is shown, and select another ComboBox Item: so, we don't need to worry about that.
So, knowing we are in an access rather than notification scenario means we are going to add either a Public property, or variable of some Type to Form2.
Technically, we are going to "inject a value" into Form2. You could also say, correctly, that we have "exposed" an integer variable in Form2 to "consumers of the class."
In this case, there's no need for the facilities a Property offers us, so we can, simply, in Form2 'sd, write something like:
public Type variableName;
Let's assume we only need to pass an integer into 'sd when it's opened:
public int WhichSerialPort;
The choice I'd
actually make here would be to use a
nullable integer for this variable:
public int? WhichSerialPort = null;
And, I'll explain that below.
Then, we can turn our attention to Form1. The action that triggers the modal showing of Form2 is, evidently, the user selecting a ComboBox Item in Form1.
So, in Form1's ComboBox SelectedIndexChanged EventHandler:
private void cmboWhichSerialPort_SelectedIndexChanged(object sender, EventArgs e)
{
sd.WhichSerialPort = cmboWhichSerialPort.SelectedIndex;
sd.ShowModal();
}
You'll note that in the above code we can set the value of 'WhichSerialPort instance of Form2 'sd before it is shown.
Then, in the Form Load EventHandler of Form2 'sd:
private void sd_Load(object sender, EventArgs e)
{
if (! WhichSerialPort.HasValue) { throw new ArgumentNullException("Serial Port to open is unspecified"); }
switch (WhichSerialPort)
{
case 0:
break;
case 1:
break;
}
}
Using a nullable integer to hold the data written into Form2 'sd from Form1 is useful as a way to guard against errors. Because an integer is a value Type, it is automatically set to #0 when it is created. By using a nullable integer, and setting it to 'null by default, we have the means to test the variable in the Form_Load EventHandler and make sure it has an integer value, rather than 'null.