如何爲comboBox1中的選定值創建公共變量,以便可以在每個按鈕中使用它,因此我無需每次都重複按鈕?對於我有的每個按鈕:如何爲combobox中的拾取項目聲明ac#變量
var portNum = comboBox1.SelectedItem.ToString();
using (SerialPort port = new SerialPort(portNum, 9600, Parity.None, 8))
但我想只是有portNum,而不必將var聲明行放在每個按鈕中。
public partial class planar232 : Form
{
private SerialPort comPort = new SerialPort();
private string[] ports = SerialPort.GetPortNames();
public planar232()
{
InitializeComponent();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
var portNum = comboBox1.SelectedItem.ToString();
using (SerialPort port = new SerialPort(portNum, 9600, Parity.None, 8))
{
byte[] bytesToSend = new byte[9] { 0x38, 0x30, 0x31, 0x73, 0x21, 0x30, 0x30, 0x31, 0x0D };
port.Open();
port.Write(bytesToSend, 0, 9);
}
}
private void button2_Click(object sender, EventArgs e)
{
var portNum = comboBox1.SelectedItem.ToString();
using (SerialPort port = new SerialPort(portNum, 9600, Parity.None, 8))
{
byte[] bytesToSend = new byte[9] { 0x38, 0x30, 0x31, 0x73, 0x21, 0x30, 0x30, 0x30, 0x0D };
port.Open();
port.Write(bytesToSend, 0, 9);
}
}