簡體   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