C# 从asp.net中的c验证textbox值(如果匹配的值=textbox.text else值=“未找到匹配项”)
我正在使用ASP.net开发一个web应用程序。在应用程序中,我调用active directory,使用下面编写的代码检查员工的别名:C# 从asp.net中的c验证textbox值(如果匹配的值=textbox.text else值=“未找到匹配项”),c#,asp.net,C#,Asp.net,我正在使用ASP.net开发一个web应用程序。在应用程序中,我调用active directory,使用下面编写的代码检查员工的别名: protected void ButtonSearch_Click(object sender, EventArgs e) { string path = "LDAP://" + "OU=UserAccounts,DC=abc,DC=corp,DC=nextel,DC=com"; string filter = "(&a
protected void ButtonSearch_Click(object sender, EventArgs e)
{
string path = "LDAP://" + "OU=UserAccounts,DC=abc,DC=corp,DC=nextel,DC=com";
string filter = "(&(objectCategory=person)(objectClass=user))";
string[] propertiesToLoad = new string[1] {"samaccountname"};
using (DirectoryEntry root = new DirectoryEntry(path))
using (DirectorySearcher searcher =
new DirectorySearcher(root, filter, propertiesToLoad))
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
string name = (string)result.Properties["samaccountname"][0];
if (name == TextBoxSearch.Text)
{
TextBoxSearch.Text = name;
}
else
{
TextBoxSearch.Text = "No match found";
}
}
}
}
我需要一个功能,我可以输入一个别名到一个文本框,而点击搜索按钮,它将是对照上述代码的结果检查。如果找到匹配项,则同一框显示该字段;如果未找到匹配项,则未找到匹配项。如何实施?以上代码仅提供未找到的匹配项
谢谢,问题:
您正在迭代结果中的所有项并覆盖文本框文本。
您只能看到结果最后一项的匹配文本
解决方案:
当找到匹配项时,需要中断循环
bool matchfound= false;
using (SearchResultCollection results = searcher.FindAll())
{
foreach (SearchResult result in results)
{
string name = (string)result.Properties["samaccountname"][0];
if (name == TextBoxSearch.Text)
{
TextBoxSearch.Text = name;
matchfound =true;
break;
}
}
}
if(!matchfound)
TextBoxSearch.Text = "No match found";
由于您正在使用TextBoxSearch.Text中的值来过滤搜索,然后只需将该值设置回TextBoxSearch.Text(如果找到该值),您可以使用LINQ将其缩短一点: 如果您只想在TextBoxSearch中显示消息,如果找不到名称,请尝试以下操作:
using (var results = searcher.FindAll().Cast<SearchResult>())
{
if (!results.Any(result => Convert.ToString(result.Properties["samaccountname"][0]) == TextBoxSearch.Text))
{
TextBoxSearch.Text = "No match found";
}
}
尽管有使用系统。Linq;在代码顶部,它表示缺少using指令。它表示'System.DirectoryServices.SearchResultCollection'不包含'any'的定义,并且没有扩展方法'any'接受类型为'System.DirectoryServices.SearchResultCollection'的第一个参数。可以找到您是否缺少using指令或程序集引用?我使用的是.NET 4.5,它始终未找到匹配项,即使输入其中存在的值。此代码始终未找到匹配项,因为我们将文本框的值显式设置为“未找到匹配项”,然后将该值与永远不匹配的名称进行比较。