2015-10-15 150 views
0

我在事件中遍歷所有連接的USB驅動器並將它們填充到Combobox中。這工作正常,但是,我現在有一個按鈕,我想用來刷新列表並將任何添加到列表中,不存在已經存在。通過USB驅動器進行迭代

這是我使用的代碼:

private void btnRefresh_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     DriveInfo[] allDrives = DriveInfo.GetDrives(); 

     foreach (DriveInfo d in allDrives) 
     { 
      if (d.IsReady == true) 
      { 
       string dl = d.VolumeLabel; 
       string dt = Convert.ToString(d.DriveType); 

       if (comboBox1.Items.Contains(comboBox1.Text)) 
       { 

       } 
       else 
       { 
        comboBox1.Items.Add(d.Name.Remove(2)); 
       } 
      } 
      comboBox1.SelectedIndex = 0; 
      comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; 
     } 
    } 
    catch { MessageBox.Show("Error retrieving Drive Information", "Error!"); } 
} 

我不知道,我已經走了,我需要另一雙眼睛,但是當我有形式打開,按下按鈕,新添加的驅動器不會填充到我的Combobox中。

任何幫助,將不勝感激。

+0

什麼代碼(具體的)部分顯示意外/不需要的行爲?漁獲?其中一個驅動器不是'IsReady'嗎?它是否是失敗的'Contains'嵌套'if'?你應該能夠通過逐步瞭解到底發生了什麼。 –

+0

這是answear http://stackoverflow.com/questions/14089342/refresh-combobox-items-easiest-way –

+0

@JᴀʏMᴇᴇ當逐步通過時,它會到達嵌套的'if'語句,然後完全忽略'else ',這是我需要它做的。如果該項目存在,則忽略它,否則,添加它。 – Sean

回答

1

在你第二次。如果你要檢查d.Name,而不是comboBox1.Text本身。您還沒有初始羣體之後,從

結算清單,我建議拉出人口代碼放到自己的方法,並從兩個和btnRefresh_Click而不是重複的邏輯調用。

新的方法將是這個樣子:

private void PopulateDrives() 
{ 
    try 
    { 
     combobox.items.clear() 
     DriveInfo[] allDrives = DriveInfo.GetDrives(); 

     foreach (DriveInfo d in allDrives) 
     { 
      if (d.IsReady == true) 
      { 
       string dl = d.VolumeLabel; 
       string dt = Convert.ToString(d.DriveType); 

       comboBox1.Items.Add(d.Name.Remove(2)); 
      } 
      comboBox1.SelectedIndex = 0; 
      comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; 
     } 
    } 
    catch { MessageBox.Show("Error retrieving Drive Information", "Error!"); } 
} 

你可以這樣簡單地調用兩地PopulateDrives()。我也只是倒你的第二個if語句整理一下有點

+0

問題,而不是改進,正是我的答案,我發佈前7分鐘... – TheLethalCoder

+1

'comboBox1.SelectedIndex = 0;' 'comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;'應該在'foreach() '和'if(d.IsReady == true)'可以被重寫爲'if(d。IsReady)' –

+0

@ user2754599爲什麼它需要超出'foreach'語句? 當然,現在它在哪裏,不管有什麼效果? – Sean

2

這條線:

if (comboBox1.Items.Contains(comboBox1.Text)) 

被檢查是否comboBox1包含comboBox1的標題文本,這確實。

你應該檢查它是否包含任何dldtd.Name

1

我建議:

private void btnRefresh_Click(object sender, EventArgs e) 
{ 
    try 
    { 
     comboBox1.Items.Clear(); 
     DriveInfo[] allDrives = DriveInfo.GetDrives(); 

     foreach (DriveInfo d in allDrives) 
     { 
      if (d.IsReady) 
      { 
       string dl = d.VolumeLabel; 
       string dt = Convert.ToString(d.DriveType); 
       comboBox1.Items.Add(d.Name.Remove(2)); 
      } 
     } 
      comboBox1.SelectedIndex = 0; 
      comboBox1.DropDownStyle = ComboBoxStyle.DropDownList; 
    } 
    catch { MessageBox.Show("Error retrieving Drive Information", "Error!"); } 
} 
+0

@ TheLethalCoder我認爲這是檢查項目是否已經存在(我錯了嗎?),我通過清除comboBox1來取代它 –