尝试将文本框值与数据集中列中的值进行比较
本文关键字:比较 集中 数据 文本 数据集 | 更新日期: 2023-09-27 18:26:28
我试图根据特定列的行值检查文本框值,我的代码可以工作,但检查了所有列,我不知道如何让它只检查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);
}
}
您可以使用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.IsNullOrEmtpty
或String.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;
}
}
你可以做:
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
}
}