I am having troubles filling a listbox from a backgroundworker thread. I currently have the following code:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var lockedUsers = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, "domain", smtu, smtp))
{
GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Users");
foreach (var userPrincipal in grp.GetMembers(false))
{
var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.SamAccountName);
if (user != null)
{
if (user.IsAccountLockedOut())
{
listBox1.Items.Add(@"domain\ " + user);
}
}
}
}
}
This returns the exception saying I cannot write to the main UI, which is correct. But I have been unable to find a way around it. I've tried the following, and although it didn't give any errors, it didn't fill the listbox.
List<string> listusers = new List<string>();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var lockedUsers = new List<UserPrincipal>();
using (var context = new PrincipalContext(ContextType.Domain, "domain", smtu, smtp))
{
GroupPrincipal grp = GroupPrincipal.FindByIdentity(context, IdentityType.SamAccountName, "Domain Users");
foreach (var userPrincipal in grp.GetMembers(false))
{
var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userPrincipal.SamAccountName);
if (user != null)
{
if (user.IsAccountLockedOut())
{
listusers.Add(@"domain\" + user);
}
}
}
}
}
private async void timerlocked_Tick(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
listBox1.DataSource = listusers;
}
Any ideas?