2012-12-18 50 views
4

如何爲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); 
     } 
    } 

回答

4

如果你的組合框只是顯示 「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); 
    } 
} 
2

創建表單範圍的屬性:

public Form Form1 
{ 
    public string PortNum {get;set;} 

    public void ComboBox1_SelectionChanged(object sender, EventArgs e) 
    { 
     PortNum = ComboBox1.SelectedItem.ToString(); 
    } 

    ... (rest of your code) 

} 
0

使用property

// this is a class member 
string PortNum 
{ 
    get { return comboBox1.SelectedItem.ToString(); } 
} 

// instead of your original code 
using (var port = new SerialPort(PortNum, ...)) { 
    ... 
} 
0

在設計時禁用按鈕1和2。

添加一個私有成員端口編號

一個SelectedItemChange事件處理程序的組合框 加入,如果選擇不爲空,將其保存在端口編號和啓用按鈕