尝试根据数据集列中的值检查文本框值

时间:2014-10-14 07:24:47

标签: c#

我试图检查特定列的行值的文本框值,我的代码工作但检查所有列,我无法弄清楚如何让它只检查CompanyName列。有什么想法吗?

 private void BTNLookupCustomer_Click(object sender, EventArgs e)
    {
        BTNUpdateCustomer.Enabled = false;
        BTNDeleteCustomer.Enabled = false;



        try
        {
            if (TXTBXCustomerLookup.Text != null)
            {
                foreach (DataTable table in ds.Tables)
                {
                    foreach (DataRow row in table.Rows)
                    {
                        foreach (object item in row.ItemArray)
                        {
                            if (item.ToString() == TXTBXCustomerLookup.Text)
                            {
                                BTNUpdateCustomer.Enabled = true;
                                BTNDeleteCustomer.Enabled = true;
                            }
                        }
                    }
                }
            }
        }
        catch (Exception err)
        {
            MessageBox.Show(err.Message);

        }
    }

2 个答案:

答案 0 :(得分:1)

您可以使用DataRow.Field<Typename>("ColumnName")

bool isEnteredNameEqual = table.AsEnumerable()
    .Any(row => row.Field<string>("CompanyName") == TXTBXCustomerLookup.Text)
BTNUpdateCustomer.Enabled = isEnteredNameEqual;
BTNDeleteCustomer.Enabled = isEnteredNameEqual;

请注意,上面使用LINQ,因此您需要在文件顶部添加using System.Linq;。另请注意,TXTBXCustomerLookup.Text != null是多余的,因为即使您指定null,TextBox.Text属性也不会返回null。您可能希望改为使用String.IsNullOrEmtptyString.IsNullOrWhiteSpace

与经典循环相同:

BTNUpdateCustomer.Enabled = false;
BTNDeleteCustomer.Enabled = false;

foreach (DataRow row in table.Rows)
{
   string companyName = row.Field<string>("CompanyName");
   if(companyName == TXTBXCustomerLookup.Text)
   {
       BTNUpdateCustomer.Enabled = true;
       BTNDeleteCustomer.Enabled = true;
       break;
   }
}

答案 1 :(得分:0)

你可以这样做:

foreach (DataRow row in table.Rows)
{

   if (row["CompanyName"].ToString() == TXTBXCustomerLookup.Text)
   {
      BTNUpdateCustomer.Enabled = true;
      BTNDeleteCustomer.Enabled = true;
      break; // condition matched break loop here no need to iterate further
   }

}