根据登录用户禁用按钮

时间:2012-06-28 13:26:00

标签: c# asp.net button visibility

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

 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 个答案:

答案 0 :(得分:0)

为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);
}

答案 1 :(得分:0)

如果要在转发器项目模板中禁用全部按钮,请尝试在要禁用控件的位置调用此方法:

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'关键字转换类型,在使用之前检查返回的对象是否为空。