我已经完成编码,并且当我运行代码时构建成功,但是我的 form1 显示为空白。下面是我的代码。
namespace AccountsApp
{
public partial class Form1 : Form
{
private List<Account> accounts = new List<Account>();
private TextBox accountNumberTextBox = new TextBox();
private TextBox clientNameTextBox = new TextBox();
private TextBox balanceTextBox = new TextBox();
private TextBox limitTextBox = new TextBox();
private TextBox interestTextBox = new TextBox();
private RadioButton checkingRadioButton = new RadioButton();
private RadioButton savingsRadioButton = new RadioButton();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void CreateAccountButton_Click(object sender, EventArgs e)
{
try
{
int number = int.Parse(accountNumberTextBox.Text);
string name = clientNameTextBox.Text;
double balance = double.Parse(balanceTextBox.Text);
if (checkingRadioButton.Checked)
{
double limit = double.Parse(limitTextBox.Text);
accounts.Add(new CheckingAccount(number, name, balance, limit));
}
else if (savingsRadioButton.Checked)
{
double interest = double.Parse(interestTextBox.Text);
accounts.Add(new SavingsAccount(number, name, balance, interest));
}
MessageBox.Show($"Total Number of accounts: {accounts.Count}");
}
catch (Exception ex)
{
MessageBox.Show($"Error: {ex.Message}");
}
}
private void ClearFields()
{
accountNumberTextBox.Clear();
clientNameTextBox.Clear();
balanceTextBox.Clear();
limitTextBox.Clear();
interestTextBox.Clear();
checkingRadioButton.Checked = true;
}
}
}
我尝试移动东西,但没有任何效果。
WinForms 中的控件很复杂,您需要进行大量设置才能让它们显示在正确的位置并按照您想要的方式运行。
例如,以下是从我的一个项目中初始化多行
TextBox
的代码:
ImageTB = new TextBox();
ImageTB.Enabled = true;
ImageTB.Location = new Point(3, 3);
ImageTB.Multiline = true;
ImageTB.Name = "ImageTB";
ImageTB.Size = new Size(518, 307);
ImageTB.TabIndex = 0;
Controls.Add(ImageTB);
这几乎是最低要求。手工完成所有这些事情很痛苦......这就是为什么我们大多数时候不手工做这些事情。
在 Visual Studio 中,我们有表单设计器来为我们处理大部分苦差事。它是生成
InitializeComponent()
中的代码的内容,包括连接事件处理程序等。您将控件拖放到画布上,设置它们的属性等,然后设计器创建按照您设计的方式构建表单所需的代码。
在 Visual Studio 中打开表单时,右键单击项目中的表单节点并选择“视图设计器”。您应该有一个包含所有控件的工具箱,选择要添加的控件(如
TextBox
),然后单击表单以放置它。使用“属性”选项卡可以设置控件名称等内容。