【发布时间】:2017-03-01 01:28:37
【问题描述】:
我已经为我的问题寻找了一些解决方案,但仍然没有找到适合我的方法。所以我注册为我的问题寻求帮助。感谢帮助。
public Form1()
{
InitializeComponent();
dataGridView1.Columns.Add("FirstNames", "FirstName");
dataGridView1.Columns.Add("SecondNames", "SecondName");
dataGridView1.Columns.Add("AccountNames", "AccountName");
dataGridView1.Columns.Add("Emailaddresses", "Emailaddress");
try
{
// enter AD settings
PrincipalContext AD = new PrincipalContext(ContextType.Domain, (ConfigurationManager.AppSettings["Domaene"]));
using (var searcher = new PrincipalSearcher(new UserPrincipal(AD)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
dataGridView1.Rows.Add
(
de.Properties["givenName"].Value,
de.Properties["sn"].Value,
de.Properties["samAccountName"].Value,
de.Properties["userPrincipalname"].Value
);
}
}
}
catch (Exception ex)
{
}
}
这就是我创建 ActiveDirectory 并将其放入 dataGridView 的方式。我正在搜索的功能是如何使用文本框搜索此 DVG。所以我已经尝试过这样的事情:
String searchValue = textBox1.Text;
int rowIndex = -1;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (row.Cells[2].Value != null) // Need to check for null if new row is exposed
{
if (row.Cells[1].Value.ToString().Equals(searchValue))
{
rowIndex = row.Index;
break;
}
}
}
此 sn-p 来自本网站的另一篇文章。我在我的构建上尝试了它,但它对我不起作用。当我在我的文本框中放一些东西时,它会抛出一个 System.NullReferenceException。问题:我真的不知道为什么它不起作用。 将不胜感激任何答案!
您好, 马文R
【问题讨论】:
-
它到底在哪里抛出了异常?哪一行?
-
if (row.Cells[1].Value.ToString().Equals(searchValue))
-
这行检查 null
if (row.Cells[2].Value != null)不应该有Cells[1]代替吗?我假设它到达新行并且Cells[1]没有值,因此不能转换为字符串,因此会引发错误。 -
如果我让它检查 foor == null 会出现同样的错误。但现在在更改的行中。
标签: c# winforms search datagridview textbox