獲得價值誠懇我看不出哪裏是自己寫的形式問題。然而,你寫的僞代碼幾乎是完美的,事實上這是做這件事的最好方式。雖然你的僞碼可以改進,因爲我要寫。 說起形式,你可以構建它以這種方式使其可重用:
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:
這裏我用複選框,但你可以改變它,並添加一個下拉樣式的組合框,然後你將擁有你所需要的。
Metro?的WinForms? WPF? Silverlight的? Windows Phone? ASP.Net? MonoTouch的? – SLaks
對不起,我認爲我用過的標籤「visual-studio-2010」不會含糊不清我關心的是「Visual C#2010 Express」(是「WinForms」嗎?) – conners
您可以同時擁有winforms和WPF在Visual C#2010 Express中,在這兩種情況下,您可能都必須編寫自己的自定義表單。 – AmazingDreams