2013-07-26 177 views
0

我想要使用每個listbox1項目來運行這兩個查詢,如果兩個結果都不同於將該項目移動到另一個名爲listbox2的列表框(如果它們與從listbox1刪除該項目相同)。將列表框項目移動到另一個列表框?

foreach (string Items in listBox1.Items) 
{ 
    using (OracleCommand crtCommand = new OracleCommand("select count(*) from((select * from all_ind_columns where index_name= '" + Items + "' and table_owner='" + txtSrcUserID.Text.ToUpper() + "'))", conn1)) 
    using (OracleCommand ctCommand = new OracleCommand("select count(*) from((select * from all_ind_columns where index_name= '" + Items + "' and table_owner='" + txtDesUserID.Text.ToUpper() + "'))", conn1)) 
    { 
     string result1 = crtCommand.ExecuteScalar().ToString(); 
     string result2 = ctCommand.ExecuteScalar().ToString(); 

     if (result1 != result2) 
     { 
      //move that item to listbox2 
     } 
     else if(result1 == result2) 
     { 
      // remove that item from listbox1 
     } 
    } 
} 
+0

然後,發生了什麼呢? –

回答

2

你不能使用foreach這裏,因爲你改變了listBox1.Items內循環, 使用while循環,並檢查listBox1.Items.Count() >0和內環路,你可以事先知情同意的第一個項目,並將其移動到第二個或刪除。

while (ListBox1.Items.Count>0) 
{ 
    var item = ListBox1.Items[0].ToString(); 

    using (OracleCommand crtCommand = new OracleCommand("select count(*) from((select * from all_ind_columns where index_name= '" + item + "' and table_owner='" + txtSrcUserID.Text.ToUpper() + "'))", conn1)) 
    using (OracleCommand ctCommand = new OracleCommand("select count(*) from((select * from all_ind_columns where index_name= '" + item + "' and table_owner='" + txtDesUserID.Text.ToUpper() + "'))", conn1)) 
    { 
     string result1 = crtCommand.ExecuteScalar().ToString(); 
     string result2 = ctCommand.ExecuteScalar().ToString(); 
     if (result1 != result2) 
     { 
      ListBox2.Items.Add(item); 
     } 
     ListBox1.Items.RemoveAt(0); 
    } 

} 

注:你的代碼是開放的SQL注入攻擊,使用的參數,而不是內嵌參數。

while (ListBox1.Items.Count>0) 
{ 
    var item = ListBox1.Items[0].ToString(); 

    using (OracleConnection con = new OracleConnection(connectionString)) 
    using (OracleCommand cmd = con.CreateCommand()) 
    { 
     con.Open(); 
     cmd.CommandText = "select count(*) from((select * from all_ind_columns where index_name= :item and table_owner=:table_owner))"; 
     cmd.Parameters.Add(item); 
     cmd.Parameters.Add(txtSrcUserID.Text.ToUpper()); 

     string result1 = cmd.ExecuteScalar().ToString(); 
     cmd.Parameters.Clear(); 
     cmd.Parameters.Add(item); 
     cmd.Parameters.Add(txtDesUserID.Text.ToUpper()); 
     string result2 = cmd.ExecuteScalar().ToString(); 

     if (result1 != result2) 
     { 
      ListBox2.Items.Add(item); 
     } 
     ListBox1.Items.RemoveAt(0); 
    } 

} 
+0

如何在while循環中使用? – user2619275

+0

這個while循環是無限的,因爲; while循環中總是有item,它不會去listbox1.items.removeAt(0);它不停止檢查循環條件?... – user2619275

+0

@ user2619275我已經改變了代碼,如果結果匹配,你需要將該項目添加到ListBox2,即使你添加或不最終你要從ListBox1刪除該項目,所以一個一個的項目將從ListBox1中刪除。沒有無限循環 – Damith

相關問題