任务需求:设计一个程序,可以输入学生的姓名、地址、职业、性别和年龄,也可以显示出来。
1.UI设计
这个界面涉及到了label,button,textbox,radiobutton,checkbox,groupbox几种控件。
姓名,地址和年龄使用的是文本框,职业采用复选框,性别选用单选按钮。
2.业务逻辑设计
将姓名,地址和年龄输入,选择复选框则为程序员,否则为非程序员。性别选择单选按钮来确认性别。
(1)*文本框需要检查是否为空,
private void txtBoxEmpty_Validating(object sender, CancelEventArgs e)
{
TextBox tb = (TextBox)sender;
if (tb.Text.Length == 0)
{
tb.BackColor = Color.Red;
}
else
{
tb.BackColor = System.Drawing.SystemColors.Window;
}
ValidateOK();
}
private void ValidateOK()
{
this.buttonOK.Enabled = (textBoxName.BackColor != Color.Red &&
textBoxAddress.BackColor != Color.Red &&
textBoxAge.BackColor != Color.Red);
}
(2)特别的,年龄文本框只能是0-9的数字。
private void textBoxAge_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
e.Handled = true; // 清除字符
}
(3)单击OK按钮后,得到一个字符串输出到文本框。
private void buttonOK_Click(object sender, EventArgs e)
{
string output;
output = "Name: " + textBoxName.Text + "\r\n";
output += "Address: " + textBoxAddress.Text + "\r\n";
output += "Occupation: " + (string)(checkBoxProgrammer.Checked ?
"Programmer": "Not a programmer") + "\r\n";
output += "Sex: " + (string)(radioButtonFemale.Checked ? "Female": "Male") + "\r\n";
output += "Age: " + textBoxAge.Text;
textBoxOutput.Text = output;
}
3. 运行结果