如何在C#中将文本框与数组进行比较

时间:2015-08-21 21:24:26

标签: c# .net arrays textbox

我在C#中很新,我无法找到答案。 我在valores变量中的数组中从我的DB获取名为NUMERO_CTA的列的值。但是我必须将这个值数组与文本框进行比较,以检查valores中包含的值之一是否与名为txtCuentaDestino的文本框的值匹配。如何将textbox.text与数组进行比较?提前致谢! 这是我的代码:

 DataTable tbl = ds.Tables[0];
     for (int i = 0; i < tbl.Rows.Count; i++)
     {
        DataRow myRow = tbl.Rows[i];
        valores = new string[] {myRow["NUMERO_CTA"].ToString()};  
     }

     if (ds.Tables[0].Rows.Count == 0)
     {
        GuardaCuenta();
        return false;
     }
     else if (txtCuentaDestino.Text == resultado)
     {
        return true;
     }
     else
     {
        return false;
     }

3 个答案:

答案 0 :(得分:3)

您无法比较字符串数组和字符串。您希望将文本框中的字符串与数组中的每个字符串进行比较,一次一个。

在这种情况下,如果要检查数组中是否有与您的文本框字符串匹配的字符串,可以使用linq方法Contains

实施例

if (arrayOfStrings.Contains(singleString))
{
    // Do something
}

答案 1 :(得分:1)

你需要遍历valores数组并进行比较。

foreach(string s in valores) 
{
    if(s == txtCuentaDestino.Text)
    {
       //do something magical
    }
}

答案 2 :(得分:1)

感谢您的回答:

两者都帮助了我很多!结果如下:

    for (int i = 0; i < tbl.Rows.Count; i++)
        {
            DataRow myRow = tbl.Rows[i];
            valores = new string[] { myRow["NUMERO_CTA"].ToString() };

            foreach (string x in valores)
            {
                if (x.Contains(cuentaDestino))
                {
                    f_Script("alerta", "<script>alert('Cuenta a crear ya Existe.');window.location.href = 'RW_CuentasBancarias.aspx';</script>");
                    contador = 1;
                }
            }

            if (contador == 1)
            {
                break;
            }
        }

        if(contador != 1){
        GuardaCuenta();
        f_Script("alerta", "<script>alert('Su cuenta ha sido creada.');window.location.href = 'RW_Solicitud_Reembolso.aspx';</script>");
        }