如何将listbox的值与c#中的表值进行比较?

时间:2014-02-28 06:35:49

标签: c# listbox sqldatareader

我在listbox1中有值,比如值为hello,hammad,cricket。我想将此列表框与名为oldTable的表中的值进行比较。如果我找到了该表中的值,那么//做其他事情//做其他事情。我正在使用此代码进行比较,但此循环无法正常工作。

while (sqlrdr.Read())
{
    for (int i = 0; i <= listBox1.Items.Count - 1; i++)
    {
        if (listBox1.Items[i].ToString() == sqlrdr[0].ToString())
        {
            listBox1.SetSelected(i, true);
            break; // TODO: might not be correct. Was : Exit For
        }
    }
}

1 个答案:

答案 0 :(得分:2)

听起来你需要这样的东西。如果这不是您所需要的,那么请更清楚地解释您想要实现的目标。

while (sqlrdr.Read())
{
    string tableValue = sqlrdr[0].ToString();
    bool found = listBox1.Items.Cast<object>().Any(x=>x.ToString() == tableValue);
    if(found)
    {
        //Search found do whatever
    }
    else
    {
        //Search not found do whatever
    }
}