根据登录用户禁用按钮



我正在接受一个用户ID,并想检查是否有任何具有相同ID的项目所有者。如果存在项目所有者,我应该只启用"下移"按钮并禁用所有其他按钮。如果存在管理员,则启用除第一次上移和最后一次下移之外的所有按钮。我想禁用除 POwner 与用户 ID 相同的按钮之外的所有按钮!(如果POwner与用户ID相同,则应启用仅向下移动按钮。

 public void Repeater1_ItemDatabound(Object Sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            String userID = User.Identity.Name.Split('\')[1];
            if (setvisibility(userID) == true) //Check if the person is Admin all buttons work 
            {
                if (e.Item.ItemIndex == 0)
                {
                    Button b = e.Item.FindControl("btnmoveup") as Button;
                    b.Enabled = false;
                }
                DataView view = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
                DataTable result = view.ToTable();
                if (e.Item.ItemIndex == (result.Rows.Count) - 1)
                {
                    Button b2 = e.Item.FindControl("btnmovedown") as Button;
                    b2.Enabled = false;
                }
            }
            else // Check if Project Owner (POwner exists) Check if userID exists in POwner
            {
                using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["ctd_priority_dbConnectionString"].ConnectionString))
                {
                    connection.Open();
                    SqlCommand cmd = new SqlCommand("Select POwner from Projects WHERE POwner = @userid", connection);
                    cmd.Parameters.AddWithValue("@userid", userID);
                    SqlDataReader reader = cmd.ExecuteReader();

为 2 个可能的角色创建(局部)布尔变量

bool isAdmin;
bool isProjectOwner;

并在启用/禁用按钮之前确定其值。

isAdmin = setvisibility(userID);
//isProjectOwner // create a similar method to setvisibility() for your project owner

现在,您只需分配或否定用户角色状态即可切换按钮可见性

...
if (e.Item.ItemIndex == 0)
{
    Button b = e.Item.FindControl("btnmoveup") as Button;
    // IS NOT admin AND IS project owner will set .Enabled = true
    b.Enabled = (!isAdmin && isProjectOwner);
}
如果要

禁用中继器项模板中的所有按钮,请尝试在要禁用控件的位置调用此方法:

private static void DisableButtonControls(RepeaterItemEventArgs e)
    {
        foreach (Control control in e.Item.Controls)
        {
            if (control is Button)
            {
                control.Visible = false;
            }
        }
    }

要在禁用所有按钮后启用向下按钮,您可以执行以下操作:

Button downButton = e.FindControl("btnmovedown") as Button;
if (downButton != null)
{
    downButton.Visible = false;
}

一个好的经验法则是,每当使用"as"关键字转换类型时,请在使用返回的对象之前检查返回的对象是否不为 null。

最新更新