如何为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);
}
}
如果您的组合框只显示"COM1"等,请执行以下操作:
using (SerialPort port = new SerialPort(comboBox1.Text, 9600, Parity.None, 8))
或者,如果您需要使用SelectedItem
,
using (SerialPort port = new SerialPort(comboBox1.SelectedItem.ToString(), 9600, Parity.None, 8))
如果你真的想要一处房产,
string SelectedPort { get { return comboBox1.SelectedItem.ToString(); } }
更好的是,重构代码,只指定按钮处理程序中的数据:
private void button1_Click(object sender, EventArgs e)
{
byte[] bytesToSend = new byte[9] { 0x38, 0x30, 0x31, 0x73, 0x21, 0x30, 0x30, 0x31, 0x0D };
this.Send(bytesToSend);
}
private void button2_Click(object sender, EventArgs e)
{
byte[] bytesToSend = new byte[9] { 0x38, 0x30, 0x31, 0x73, 0x21, 0x30, 0x30, 0x30, 0x0D };
this.Send(bytesToSend);
}
private void Send(byte[] bytesToSend)
{
var portNum = comboBox1.SelectedItem.ToString();
using (SerialPort port = new SerialPort( portNum, 9600, Parity.None, 8))
{
port.Open();
port.Write(bytesToSend, 0, bytesToSend.Length);
}
}
在表单范围中创建属性:
public Form Form1
{
public string PortNum {get;set;}
public void ComboBox1_SelectionChanged(object sender, EventArgs e)
{
PortNum = ComboBox1.SelectedItem.ToString();
}
... (rest of your code)
}
使用属性:
// this is a class member
string PortNum
{
get { return comboBox1.SelectedItem.ToString(); }
}
// instead of your original code
using (var port = new SerialPort(PortNum, ...)) {
...
}
在设计时禁用按钮1和2。
添加私人成员PortNum
将SelectedItemChange事件处理程序添加到组合框如果选择不为空,则将其保存在PortNum中并启用按钮