title: How to declare a c# variable for a picked item from a combobox
body: <p>How do I create a public variable for a selected value in my comboBox1 so that it can be used in every button so I don't have to repeat it for every button?  For every button I have:</p>
  
  <pre><code>var portNum = comboBox1.SelectedItem.ToString();
  using (SerialPort port = new SerialPort( portNum, 9600, Parity.None, 8))
  </code></pre>
  
  <p>But I want to just have portNum and not have to put the var declaration line in every button.</p>
  
  <pre><code>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);
          }
      }
  </code></pre>