我的目标是:
- 用户在组合框中键入完整或部分计算机名
- 按钮单击事件启动后台工作人员将计算机名传递给 DoWork 方法
- DoWork 方法在 ActiveDirectory 中搜索计算机名并将集合传递给 WorkerCompleted 方法
- WorkerCompleted 方法将每个计算机名添加到组合框项中。
我的错误出现在我的 backgroundWorker_RunWorkerCompleted 方法中的 foreach 循环中。
- “foreach 语句不能对 'object' 类型的变量进行操作,因为 'object' 不包含 'GetEnumerator' 的公共定义”
如果我做一个 MessageBox.Show(results.First().ToString()); 在 DoWork 方法中,我可以查看集合中的第一个计算机名。
如果我做一个 MessageBox.Show(e.Result.ToString()); 在 DoWork 和 WorkerCompleted 方法中,我得到了这个:
- “System.DirectoryServices.AccountManagement.PrincipalSearchResult`1[System.DirectoryServices.AccountManagement.Principal]”
对此的任何指导将不胜感激!
private void button1_Click(object sender, EventArgs e)
{
//Saves computername entered by user to pass into DoWork method
string PCName = comboBox1.Text;
//Start background thread passing computer to the Dowork method
backgroundWorker1.RunWorkerAsync(PCName);
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
{
//Setup Filter
ComputerPrincipal computer = new ComputerPrincipal(ctx);
computer.Name = "*" + e.Argument + "*";
//Search for PC
PrincipalSearcher ps = new PrincipalSearcher();
ps.QueryFilter = computer;
//Get Results
PrincipalSearchResult<Principal> results = ps.FindAll();
//results will be passed to RunWorkerCompleted
e.Result = results;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Add each computername to combobox
foreach (object PC in e.Result) // <--------------- ERROR HERE!
{
comboBox1.Items.Add(PC.ToString());
}
}
}