如何为我的 comboBox1 中的选定值创建一个公共变量,以便它可以在每个按钮中使用,这样我就不必为每个按钮重复它?对于我拥有的每个按钮:
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);
}
}