简体   繁体   中英

Get result from Linq Query

I am trying to check if IsAdmin is true which is a bool. If it is true then a checkbox is checked in the gridview EditItemTemplate.

The query is when a gridview is in edit mode and the user that is being edited is already admin.The checkBox needs to be checked if that is true because if they update the row and the checkbox is not checked they are not longer admin.

What I am thinking is that the query should be able to do this. But not sure how to implement the IsAdmin == true.

private void LoadGridEdit()
{
using (dbDataContext _db = new dbDataContext())
{
    var result = from u in _db.tbl_Users
                    where u.Deleted == false
                select new
                        {
                            u.UserId,
                            u.UserName,
                            u.Email,
                            u.IsAdmin,
                            u.tbl_ServiceArea.ServiceArea,
                        };

    if ()
    {
        //????   or foreach?
    }
    // Bind Here
}
}

I have had a look about and tried different options but I am not sure.

Have you tried using a CheckBox in your GridView template, and set its Checked property to bind to the IsAdmin value, something like this :

<asp:CheckBox ID="chbIsAdmin" runat="server" Checked='<%# Bind("IsAdmin") %>' />

Edit:

Sorry, I just read about the admin removing their own privileges accidentally. If I were in your boot, I won't let this thing happens. An admin cannot remove their own privileges. This ensure at least there are 1 admin exists.

此LinQ查询将返回IEnumerable对象,您可以使用foreach语句枚举它。

Something like that:

var result = _db.tbl_Users.Where(u=> u.Deleted == false).Select(e=> new
                    {
                        u.UserId,
                        u.UserName,
                        u.Email,
                        u.IsAdmin,
                        u.tbl_ServiceArea.ServiceArea,
                    }.ToList();

foreach(var res in result)
{
    if(res.IsAdmin)
    {
     // Do SOmething
    }
}

Sorry, but i dislike the sql-like linq, so i wrote like that. Hope it will be helpfull.

result will return an IEnumerable through your objects that contain a property IsAdmin . If you want to do an action for each element that has IsAdmin == true do as follows:

var resultsWithAdminIsTrue = from r in result
                             where r.IsAdmin
                             select r;

foreach (var r in resultsWithAdminIsTrue)
{
    /* Do action */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM