C# 是否将列表框项目移动到另一个列表框?
我想使用每个listbox1项来运行这两个查询,如果两个结果不相同,则将该项移动到另一个名为listbox2的列表框中,如果它们相同,则从listbox1中删除该项C# 是否将列表框项目移动到另一个列表框?,c#,listbox,listboxitem,C#,Listbox,Listboxitem,我想使用每个listbox1项来运行这两个查询,如果两个结果不相同,则将该项移动到另一个名为listbox2的列表框中,如果它们相同,则从listbox1中删除该项 foreach (string Items in listBox1.Items) { using (OracleCommand crtCommand = new OracleCommand("select count(*) from(( select * from all_ind_columns where index_n
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
}
}
}
您不能在此处使用
foreach
,因为您更改了循环中的listBox1.Items
,
使用while循环并检查listBox1.Items.Count()>0
,在循环内,您可以pic第一个项目并将其移动到第二个项目或删除
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循环?这个while循环是无限的,因为;while循环中始终存在项,它不会转到listbox1.items.removeAt(0);它没有停止检查循环条件?..@user2619275我已经更改了代码,如果结果匹配,您需要将该项添加到ListBox2,即使您添加或不添加,最终您也将从ListBox1中删除该项,因此将逐个从ListBox1中删除该项。没有无限循环请注意,我的第二个ctCommand在txtDesUserID.Text.ToUpper()@user2619275处不同。注意到了,这就是我再次设置参数值的原因
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);
}
}