基于广告组成员身份显示/隐藏按钮-C#

基于广告组成员身份显示/隐藏按钮-C#,c#,windows-forms-designer,C#,Windows Forms Designer,正在尝试根据Active Directory中的组成员身份显示/隐藏我的按钮,但失败。使用以下代码: private void AlterControlAppearance() { string username = System.Environment.UserName; PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain");

正在尝试根据Active Directory中的组成员身份显示/隐藏我的按钮,但失败。使用以下代码:

    private void AlterControlAppearance()
    {

        string username = System.Environment.UserName;

        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain");
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
        GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "myadgroup");

        if (user != null)
        {

            if (user.IsMemberOf(group))
            {
                button1.Visible = true;
            }
            else
            {
                button1.Visible = false;
            }
        }
    }
如果我将代码移动到private void InitializeComponent()(下面的代码),它可以完美地工作,但这只是在调试时让它工作的一个解决方案。表单设计器将停止工作,因为您不应该编辑任何设计器生成的代码

        // 
        // button1
        // 
        this.button1.Location = new System.Drawing.Point(12, 22);
        this.button1.Name = "button1";
        this.button1.Size = new System.Drawing.Size(208, 23);
        this.button1.TabIndex = 1;
        this.button1.Text = "MyButton";
        this.button1.UseVisualStyleBackColor = true;
        this.button1.Click += new System.EventHandler(this.button1_Click);
        {

            string username = System.Environment.UserName;

            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "mydomain");
            UserPrincipal user = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, username);
            GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "myadgroup");

            if (user != null)
            {

                if (user.IsMemberOf(group))
                {
                    button1.Visible = true;
                }
                else
                {
                    button1.Visible = false;
                }
            }
        }

我错过了什么?我已经在谷歌上搜索了几个小时,但运气不好,这可能是我糟糕的搜索技能。。。提前感谢您的帮助!:)

从表单的
Load()
事件调用您的
AlterControlAppearance()
方法。谢谢,@Idle\u Mind!现在我觉得自己很愚蠢,但你每天都能学到新东西。没问题……而且绝对不会觉得自己愚蠢。每个人都去过那里;我们的编码之旅必须从某个地方开始,对吗?继续学习!前进…=)