我建议您使用 Add|New Item|Windows Form 创建一个新表单。然后,您将获得一个设计图面,您可以在其中添加一个列表框,并生成将正确初始化您的表单和列表框的代码。特别是您的表单和列表框将获得它们当前没有的默认大小。
您的代码(例如 Form1.cs)将与此类似:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.listBox1.DataSource = new List<int> { 1, 2, 3, 4 };
}
public int? SelectedValue
{
get
{
return (int?)this.listBox1.SelectedValue;
}
}
}
另外,Form1.Designer.cs 中会有大量代码,类似于
....
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.listBox1 = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// listBox1
//
this.listBox1.FormattingEnabled = true;
this.listBox1.Location = new System.Drawing.Point(30, 37);
this.listBox1.Name = "listBox1";
this.listBox1.Size = new System.Drawing.Size(120, 95);
this.listBox1.TabIndex = 0;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.listBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
你可以像这样使用你的表格:
private void button1_Click(object sender, System.EventArgs e)
{
using (var form = new Form1()) // you should dispose forms used as dialogs
{
if (DialogResult.OK == form.ShowDialog()) // optional (you could have OK/Cancel buttons etc
{
Debug.WriteLine(form.SelectedValue ?? -1);
}
}
}