如何为Windows窗体中的每个可能的枚举值创建一个复选框?

myW*_*SON 0 .net c# reflection dialog winforms

假设我们有一个enum Identifier {Name, Id, Number},我们希望为用户提供一个消息,如对话框,每个可能的Identifier值和Ok按钮只有复选框.在对话框确认中获取a List<Identifier>(如果未选中任何复选框,则为空).如何用winforms做这么简单的事情?

rcl*_*ent 6

您可以在枚举中获取一系列值:

var valuesArray = Enum.GetValues(typeof (Identifier));
Run Code Online (Sandbox Code Playgroud)

要显示复选框:

foreach (var val in valuesArray)
{
    //create checkbox
    var cb = new CheckBox();
    cb.Name = string.Format("cb_{0}", val);
    cb.Text = val; //set your properties

    //add to your form controls
    this.Controls.Add(cb);
}
Run Code Online (Sandbox Code Playgroud)

要获取列表,只需获取表单上的所有复选框:

var checkedIdentifiers = new List<Identifier>();
foreach (var val in valuesArray)
{
    //find checkbox
    var cb = this.Controls[string.Format("cb_{0}", val)];
    if (cb != null && cb.Checked)
        checkedIdentifiers.Add((Identifier)Enum.Parse(typeof(Identifier), val));
}
Run Code Online (Sandbox Code Playgroud)

您可以对上面的其他错误检查,但这是它的要点.