2016-09-27 8 views
1

私のアプリケーションをC#でシリアルポートをリフレッシュできるようにしたい。ポートのリスト(コンボボックス内)が空で、私がボタンrefreshを押すと、それは完全に動作し、アクティブなポートのリストを表示します。私がSerial Portを切断してrefreshボタンを押すと、実際にはシリアルポートが切断されているため、(Comboboxの)ポートのリストを空にする必要があります。だから私がrefreshボタンを押して、条件が切断されたとき、私たちは(コンボボックスで)すべてのポートリストを空にする方法を作るのですか?C#でシリアルポートをリフレッシュする方法#

これはリフレッシュボタンで私のコードです:

private void button2_Click_2(object sender, EventArgs e) 
{ 
    if(String.IsNullOrEmpty(cboPort.Text)) 
    { 
     comm.SetPortNameValues(cboPort); 

     for (int i = 0; i < cboPort.Items.Count; i++) 
     { 
      string value = cboPort.GetItemText(cboPort.Items[i]); 

      if (String.IsNullOrEmpty(value)) 
      { 
       string a = cboPort.SelectedIndex.ToString(); 
       return; 
      } 
      else 
      { 
       cboPort.SelectedIndex = 0; 
      } 
     } 
    } 
    else if ((cboPort.Text) != " " && cboPort.SelectedIndex == -1) 
    { 
      cboPort.Text = " "; 
      return; 
    } 
} 

これはsetportnamevaluesで私のコードです:

public void SetPortNameValues(object obj) 
    { 
     foreach (string str in SerialPort.GetPortNames()) 
     { 
      ((ComboBox)obj).Items.Add(str); 
     } 
    } 

私expetationは次のとおりです。助けるため

1. i connect serial port 2. i run my app 3. i disconnect serial port 4. i hit refresh 5. final result is port list empty in combobox

感謝し、応答、私はまだC#で​​新しいです。ご挨拶!

答えて

0

i最後に答えを得てください。

これはsetportnamevaluesの変形例である:ボタンアクションでは、ここで変更で

public void SetPortNameValues(object obj) 
    { 
     string[] ports = SerialPort.GetPortNames(); // load all name of com ports to string 
     ((ComboBox)obj).Items.Clear(); //delete previous names in combobox items 

     foreach (string port in ports) //add this names to comboboxPort items 
     { 
      ((ComboBox)obj).Items.Add(port); //if there are some com ports ,select first 
     } 
     if (((ComboBox)obj).Items.Count > 0) 
     { 
      ((ComboBox)obj).SelectedIndex = 0; 
     } 
     else 
     { 
      ((ComboBox)obj).Text = " "; //if there are no com ports ,write Empty 
     } 
    } 

private void button2_Click_2(object sender, EventArgs e) 
    { 
     comm.SetPortNameValues(cboPort); 
    } 

ええ、最終的には私が欲しいものを手に入れます。

関連する問題