Perf
Perf

Reputation: 23

Automatically update a datagridview

Datagrid View in a form gets populated from a List I have this Form with a datagridview that gets populated from a List. When i click on the Users button on each row, a list of users also in a datagrid should appear

The datagrid on the new form gets updated by the list i pass, When i click on the Users button this is what happens:

 GetUserDescriptorDetails gtUserDetails = new GetUserDescriptorDetails(name, xmlData, CreateListDynamically(name));
 gtUserDetails.ShowDialog();

the CreateListDynamically method is like this:

 public BindingList<xml.UserDescriptor> CreateListDynamically(string _name)
    {
        foreach (xml.UserDescriptor dbList in xmlData.Users)
        {
            if (dbList.DatabaseDescriptorName == _name)
            {
                users.Add(new xml.UserDescriptor() { DatabaseDescriptorName = dbList.DatabaseDescriptorName, Username = dbList.Username, Password = dbList.Password, IsAdmin = dbList.IsAdmin });
            }

        }
        return users;
    }

Now the list is fine, but every time i click on the Users button the rows duplicate, because of the users.Add. How can i solve this? The fact that i add values is only to populate the list, is there any other way to get the list with the condition:

dbList.DatabaseDescriptorName == _name

Upvotes: 0

Views: 108

Answers (1)

Bernd Linde
Bernd Linde

Reputation: 2152

Inside your CreateListDynamically(string _name) method, you are never clearing the previous users list, this will be why you are getting the duplication.
Add a users.Clear() before your foreach loop and the duplication should go away.

This all ofc assumes that users is a class variable since I do not see it being passed into the method as a variable

What you could also do is entirely decouple the users variable and just have a temporary variable for your resultset inside your method:

public BindingList<UserDescriptor> CreateListDynamically(string _name)
{
  return new BindingList<UserDescriptor>(xmlData.Users.FindAll(x => x.DatabaseDescriptorName == _name));
}

Upvotes: 1

Related Questions