真诚地,我看不出自己编写表格的问题出在哪里。但是,您编写的伪代码几乎是完美的,实际上这是最好的方法。尽管我要写的时候你的伪代码可以改进。说到表单,您可以以这种方式构造它以使其可重用:
class myForm : Form{
public int Result;
private Label lblText;
private Button btnOk, btnCancel;
private CheckBox[] checkboxes;
public myForm(string text, params string[] choicesText){
//set up components
lblText = new Label(){
Text = text,
AutoSize = true,
Location = new Point(10, 10)
//...
};
checkboxes = new CheckBox[choicesText.Length];
int locationY = 30;
for(int i = 0; i < checkboxes.Length; i++){
checkboxes[i] = new CheckBox(){
Text = choicesText[i],
Location = new Point(10, locationY),
Name = (i + 1).ToString(),
AutoSize = true,
Checked = false
//...
};
locationY += 10;
}
btnOk = new Button(){
Text = "OK",
AutoSize = true,
Location = new Point(20, locationY + 20)
//...
};
btnOk += new EventHandler(btnOk_Click);
//and so on
this.Controls.AddRange(checkboxes);
this.Controls.AddRange(new Control[]{ lblText, btnOk, btnCancel /*...*/ });
}
private void btnOk_Click(object sender, EventArgs e){
Result = checkboxes.Where(x => x.Checked == true).Select(x => Convert.ToInt32(x.Name)).FirstOrDefault();
this.Close();
}
}
然后在主窗体中:
using(myForm form = new myForm("Select a choice", "choice 1", "choice 2")){
form.ShowDialog();
int result = form.Result;
switch(result){
case 1: MessageBox.Show("You checked choice 1") ; break;
case 2: MessageBox.Show("You checked choice 2") ; break;
default: MessageBox.Show("Invalid choice"); break;
}
}
PS:
在这里我使用了复选框,但您可以更改它并添加具有下拉样式的组合框,然后您将拥有所需的内容。