1

I am trying to show multiple records from database in datagridview but I'm having only a single record all the time.
2 tables are involved in this query, from 1st table I acquire all the id's those fulfill the condition and from 2nd table I am getting the user information.
1st table is tblUsers_Roles and 2nd is tblUsers.
These tables have primary/foriegn key relationship.
Here is my code:

IEnumerable<tblUsers_Role> id = db.tblUsers_Role.Where(a => a.User_Role == selectRole);

foreach (var user in id)
{
    var userinfo = from b in db.tblUsers 
                   where b.User_Id == user.User_Id 
                   select new { b.First_Name, b.Last_Name, b.Status, b.Authenticated };

    dgvResults.DataSource = userinfo.ToList();
    dgvResults.Show();
}

1 Answer 1

2

You are assigning the grid in the loop. That is not going to work. Maybe something like this will work:

var userinfo =(from ur in db.tblUsers_Role
    join u in db.tblUsers
        on ur.User_Id equals u.User_Id 
    where ur.User_Role == selectRole
    select new
    {
        u.First_Name, 
        u.Last_Name, 
        u.Status, 
        u.Authenticated
    }).ToList();

dgvResults.DataSource = userinfo;
dgvResults.Show();

Or a alteretive would be like this:

 var roles=db.tblUsers_Role
             .Where(a => a.User_Role == selectRole)
             .Select (a =>a.User_Id).ToList();

var userinfo=
    (
        from u in db.tblUsers
        where roles.Contains(u.User_Id)
        select new
        {
            u.First_Name, 
            u.Last_Name, 
            u.Status, 
            u.Authenticated
        }
    ).ToList();

dgvResults.DataSource = userinfo;
dgvResults.Show();

Not as nice as the first one. But maybe you understand the concept.

Sign up to request clarification or add additional context in comments.

1 Comment

i will:) by the way first solution was beautiful!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.