I'm trying to query LDAP for a list of PC names, and input them into a DataTable. I can get the query to run, and input them directly into a ListBox, but I'm not able to sort that way, which is why I'm trying to use a DataTable.
I think the issue with the code above is the DataTable, adding rows to the DataTable, and then binding it to the DataTable.
If I replace
with
then the PC names are added to the list box. The problem is that they are not sorted. I'm not able to add items to an array prior to the listbox in the foreach loop either.
Any ideas? I'm thinking I need to create a new row for every item returned by the search. Also, if anyone knows a way to sort my search results, I could do that and bypass the datatable.
Code:
public void ldapQuery()
{
string server = ""; //Insert Domain controller server here
string adminUser = ""; //Insert an admin user account here
string adminPass = ""; //Password for above username
DirectoryEntry de = new DirectoryEntry();
de.Path = "LDAP://" + server + "";
de.Username = adminUser;
de.Password = adminPass;
try
{
DirectorySearcher ser = new DirectorySearcher();
ser.Filter = "(&ObjectCategory=computer)"; //Only allows Computers to be returned in results.
SearchResultCollection results = ser.FindAll();
DataTable dt = new DataTable();
DataRow pcRow;
pcRow = dt.NewRow();
foreach (SearchResult res in results)
{
string[] temp = res.Path.Split(','); //temp[0] would contain the computer name ex: cn=computerName
pcRow["pcName"] = temp[0].Substring(10);//returns everything after LDAP://CN= until end of temp[0].
}
dt.Rows.Add(pcRow);
lbItems.DataSource = dt;
lbItems.DisplayMember = "pcName";
lbItems.ValueMember = "pcName";
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
de.Dispose();//Clean up resources
}
}
I think the issue with the code above is the DataTable, adding rows to the DataTable, and then binding it to the DataTable.
If I replace
Code:
pcRow["pcName"] = temp[0].Substring(10);//returns everything after LDAP://CN= until end of temp[0].
with
Code:
lbItems.Items.Add(temp[0].Substring(10));
then the PC names are added to the list box. The problem is that they are not sorted. I'm not able to add items to an array prior to the listbox in the foreach loop either.
Any ideas? I'm thinking I need to create a new row for every item returned by the search. Also, if anyone knows a way to sort my search results, I could do that and bypass the datatable.