繁体   English   中英

多单选按钮点击事件

[英]Multi radiobutton Click Event

任何人都知道为什么这段代码不起作用?

代码应该做的是获取列表中的所有用户并为他们制作单选按钮,然后每次单击它将获取每个用户 class 列表中的文本并将它们添加到文本框中

但问题是它只适用于最后添加的单选按钮,并不是所有的单选按钮都知道为什么。

 private void UserMessages()
    {
        int y = 8;
        int x = 7;
        
        if (TheClients.Count > 0)
        {
            foreach (HandleClients C1 in TheClients)
            {
                RB = new RadioButton();
                RB.Text = C1.ClientUser;
                RB.Location = new Point(x, y);
                RB.Font = PL_UsersCont.Font;
                RB.Visible = true;
                RB.AutoSize = true;
                RB.ForeColor = Color.Black;
                RB.FlatStyle = FlatStyle.Flat;
                PL_UsersCont.Controls.Add(RB);
                y += RB.Height;
            }
            RB.Click += RB_Click;
        }

    }

private void RB_Click(object sender, EventArgs e)
    {
        foreach (HandleClients MSGS in TheClients)
        {
            if (RB.Text == MSGS.ClientUser)
            {
                TXB_MSGS.Text = string.Empty;
                foreach (string M in MSGS.ClientMessages)
                {
                    TXB_MSGS.Text += M + "\r\n";
                }
            }
        }   
    }

我可以在代码中看到两个问题。 第一个是将处理程序分配给Click事件。 要解决此问题,您需要移动该行

RB.Click += RB_Click;

foreach循环内。 就目前而言,您的代码只是为最后创建的RadioButton添加事件处理程序,而不是为您创建的每个 RadioButton 添加事件处理程序。

第二,您还会发现RB_Click事件处理程序有问题。 为确保选中的 RadioButton 已更新,请将这行代码添加到foreach循环中:

RB.Tag = C1;

然后将RB_Click处理程序更改为:

private void RB_Click(object sender, EventArgs e)
{
    RadioButton thisRadioButton = sender as RadioButton;

    if (thisRadioButton != null)
    {
        HandleClients MSGS = thisRadioButton.Tag as HandleClients;
        TXB_MSGS.Text = string.Empty;

        TXB_MSGS.Text += String.Join (Environment.NewLine, MSGS.ClientMessages);
    }   
}

此代码现在仅适用于单击的RadioButton

最简单的方法是完全避免使用RB_Click方法。

尝试这个:

private void UserMessages()
{
    int y = 8;
    int x = 7;

    if (TheClients.Count > 0)
    {
        foreach (HandleClients C1 in TheClients)
        {
            var rb = new RadioButton()
            {
                Text = C1.ClientUser,
                Location = new Point(x, y),
                Font = PL_UsersCont.Font,
                Visible = true,
                AutoSize = true,
                ForeColor = Color.Black,
                FlatStyle = FlatStyle.Flat,
            }
            rb.Click += (s, ea) => TXB_MSGS.Text = String.Join(Environment.NewLine, C1.ClientMessages);
            PL_UsersCont.Controls.Add(rb)
            y += rb.Height;
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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