Rajendra Purant Rajendra Purant - 1 year ago 213
C# Question

c# - Add list of strings to the DataGridView when the DataSource is already bonded to DataGridView

I am working on a project where I need to develop a functionality to assign/modify/remove Roles to the User

I have a list of User Roles attached to the DataGridView's DataSource as below.

dgvAssignedRoles.DataSource = _userBll.ReadUserRoles(userId);

Which looks like below:


I would like to add few more roles (like e.g., HR_Admin, Manager_Role, EndUser_Role, etc.) to the user, which will be fetched from list of Roles from another form

RoleList Form -

// Global Declaration
public List<string> SeletedRoleList { get; set; }

// Inside the Add function
SeletedRoleList = new List<string>();
foreach (DataGridViewRow row in dgvDataList.Rows)
if (row.Selected)
string str = row.Cells[0].Value.ToString();

And the I am trying to add these
to DataGridView which already have some roles, but it is throwing an error below.

User Form -

var rolelistform = new RoleList();

foreach (var v in rolelistform.SeletedRoleList)

Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.

I know once the DataSource property is used to bind to data you cannot explicitly add rows directly to the DataGridView.

Anyone have an idea how could I achieve this and add the rows explicitly to DataSource property.


Answer Source

Finally I figured out the best solution by myself.

In User form, declared a global List<string> variable

// Global Declaration    
private static List<string> AssignedRoleList { get; set; }

Then assigned the existed user roles to this global variable AssignedRoleList and bounded the user roles data to DataGridView. Below is the code.

AssignedRoleList = new List<string>();
AssignedRoleList = _userBll.ReadUserRoles(userId);
if (AssignedRoleList.Count > 0)
    var source = new BindingSource {DataSource = AssignedRoleList.Select(x => new {Roles = x})};
    dgvAssignedRoles.DataSource = source;

Then after I added the new SelectedRoleList to AssignedRoleList and bounded it to DataGridView.

NewRoleList = new List<string>();
// Assigned Old user roles to the new one.
if (AssignedRoleList != null) NewRoleList = AssignedRoleList;

foreach (var v in dataviewform.SeletedDataList)
    bool status = true;
    // Check if user already have the roles
    if (dgvAssignedRoles.Rows.Cast<DataGridViewRow>().Any(row => Equals(row.Cells[0].Value, v)))
        MessageBox.Show("Role already exist.");
        status = false;
    // Adding the new selected roles to the existence user role if not present
    if (status)
    // Finally attaching the both new and old user roles to datagridview
    var source = new BindingSource {DataSource = NewRoleList.Select(x => new {Roles = x})};
    dgvAssignedRoles.DataSource = source;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download