我有这个创建单选按钮的代码,当我单击按钮时,当单击按钮检查单选按钮时,有人可以向我显示单独选择每个按钮的代码吗?如何使每个单选按钮的文本不同?
private void createButtons()
{
flowLayoutPanel1.Controls.Clear();
for(int i = 0;i <10;i++)
{
RadioButton b = new RadioButton();
b.Name = i.ToString();
b.Text = "radiobutton" + i.ToString();
b.AutoSize = true;
flowLayoutPanel1.Controls.Add(b);
}
}
答案 0 :(得分:1)
每个按钮的文字已经不同了。当您在for
循环中移动时,您将在末尾附加一个数字。听起来你只需要在动态创建的单选按钮的CheckedChanged
事件上添加一个处理程序,这样你就可以根据点击的那个做一些事情。
您只需要将此行添加到for
循环中的构建步骤:
b.CheckedChanged += RadioButtonClicked;
然后定义适当的方法:
private void RadioButtonClicked(object sender, EventArgs e)
{
var radioButton = (RadioButton)sender;
// Only run on checked items (per your comments).
// This condition will cause the uncheck action/event to exit here.
if (!radioButton.Checked)
{
return;
}
// Alternately, you could use a switch statement.
if (radioButton.Name == "1")
{
// do something...
}
else if (radioButton.Name == "2")
{
// do something else...
}
// ...
}
答案 1 :(得分:1)
根据您的评论,我建议您使用常规Button
代替RadioButton
。
以下是为每个消息显示唯一消息的实现:
private void createButtons()
{
flowLayoutPanel1.Controls.Clear();
for (int i = 1; i <= 65; i++)
{
Button b = new Button();
b.Name = i.ToString();
b.Text = "Translate" + i.ToString();
b.Click += b_Click;
flowLayoutPanel1.Controls.Add(b);
}
}
void b_Click(object sender, EventArgs e)
{
Button b = sender as Button;
string TextBoxValue = string.Empty;
switch (b.Name)
{
case "1":
TextBoxValue = "Get the Translation for item # 1 here";
break;
case "2":
TextBoxValue = "Get the Translation for item # 2 here";
break;
// ETC.... 3,4,5
default:
TextBoxValue = "Button #(" + b.Name + ") is not handled";
break;
}
MessageBox.Show(this, TextBoxValue, "Translation");
}