代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 单选按钮控件
{
public enum eMs { 状态1, 状态2, 状态3 };
class Program
{
static void Main(string[] args)
{
Console.WriteLine("dddd");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Myform());
}
}
class Myform : Form {
EnumRidioButtonList enumRidioButtonList = new EnumRidioButtonList();
Button button1 = new Button();
TextBox textBox = new TextBox();
public Myform() {
createButton();
textBox.Location = new System.Drawing.Point(150, 50);
this.Controls.Add(enumRidioButtonList);
this.Controls.Add(button1);
this.Controls.Add(textBox);
enumRidioButtonList.set(typeof(eMs));
}
private void createButton() {
this.button1.Location = new System.Drawing.Point(0,50);
this.button1.Text = "button1";
this.button1.Click += new System.EventHandler(this.button3_Click);
}
private void button3_Click(object sender, EventArgs e)
{
eMs ems = (eMs)enumRidioButtonList.getSelect();
int a = (int)ems;
textBox.Text = a.ToString();
}
}
class EnumRidioButtonList: UserControl {
private Type myType;
private System.Collections.Generic.List<RadioButton> clist = new System.Collections.Generic.List<RadioButton>();
private System.ComponentModel.IContainer components = null;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
public void set(Type type)
{
this.myType = type;
InitializeComponent();
}
private void InitializeComponent()
{
int i = 0;
foreach (var a in Enum.GetValues(myType))
{
RadioButton radioButton = createRadioButton(i++, a.ToString());
clist.Add(radioButton);
}
foreach (RadioButton r in this.clist)
{
this.Controls.Add(r);
}
//
// EnumRidioButton
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Name = "EnumRidioButton";
this.Size = new System.Drawing.Size(381, 40);
this.ResumeLayout(false);
this.PerformLayout();
}
private RadioButton createRadioButton(int i, string text)
{
RadioButton radioButton1 = new RadioButton();
this.SuspendLayout();
//
// radioButton1
//
radioButton1.AutoSize = true;
radioButton1.Location = new System.Drawing.Point(i * 120, 0);
radioButton1.Name = "radioButton1";
radioButton1.Size = new System.Drawing.Size(95, 16);
radioButton1.TabIndex = 0;
radioButton1.TabStop = true;
radioButton1.Text = text;
radioButton1.UseVisualStyleBackColor = true;
return radioButton1;
}
public Object getSelect()
{
Object ret = 0;
foreach (RadioButton r in this.clist)
{
if (r.Checked == true)
{
ret = Enum.Parse(myType, r.Text);
break;
}
}
return ret;
}
}
}
运行