目录
????????利用条件语句判断用户登录身份,根据用户登录身份的不同,给予相应的操作权限。
? ? ? ? 主要用if语句及ComboBox控件。其中,ComboBox是窗体中的下拉列表控件,在使用ComboBox控件前,可以先向ComboBox控件的Items集合中添加下拉列表中将要显示的对象(一般为字符串对象),由于Items集合的Add方法接受Object对象,所以任何对象都可以放入Items集合中,ComboBox控件在显示下拉列表时会自动调用Items集合中每一个Object对象的ToString方法,得到字符串对象,并在ComboBox控件中显示。
// 用条件语句判断用户登录身份
namespace _028
{
public partial class Form1 : Form
{
private GroupBox? groupBox1;
private Button? button1;
private ComboBox? comboBox1;
private Label? label1;
public Form1()
{
InitializeComponent();
Load += Form1_Load;
}
private void Form1_Load(object? sender, EventArgs e)
{
//
// button1
//
button1 = new Button
{
Location = new Point(105, 76),
Name = "button1",
Size = new Size(75, 23),
TabIndex = 2,
Text = "登录",
UseVisualStyleBackColor = true
};
button1.Click += Button1_Click;
//
// comboBox1
//设置DropDownStyle属性为DropDownList,这样可以使用户选择的项为只读
comboBox1 = new ComboBox
{
FormattingEnabled = true,
Location = new Point(135, 27),
Name = "comboBox1",
Size = new Size(121, 25),
TabIndex = 1,
DropDownStyle = ComboBoxStyle.DropDownList
};
comboBox1.Items.AddRange(["admin","user"]);
//
// label1
//
label1 = new Label
{
AutoSize = true,
Location = new Point(60, 35),
Name = "label1",
Size = new Size(43, 17),
TabIndex = 0,
Text = "用户登录:"
};
//
// groupBox1
//
groupBox1 = new GroupBox
{
Dock = DockStyle.Fill,
Location = new Point(0, 0),
Name = "groupBox1",
Size = new Size(284, 111),
TabIndex = 0,
TabStop = false,
Text = "登录"
};
groupBox1.Controls.Add(button1);
groupBox1.Controls.Add(comboBox1);
groupBox1.Controls.Add(label1);
groupBox1.SuspendLayout();
//
// Form1
//
AutoScaleDimensions = new SizeF(7F, 17F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(284, 111);
Controls.Add(groupBox1);
Name = "Form1";
StartPosition = FormStartPosition.CenterScreen;
Text = "判断用户登录身份";
groupBox1.ResumeLayout(false);
groupBox1.PerformLayout();
ResumeLayout(false);
}
private void Button1_Click(object? sender, EventArgs e)
{
if (comboBox1!.SelectedItem!.//判断用户登陆信息
ToString() == "admin")
{
MessageBox.Show( //如果是admin登陆则提示管理员登陆
"管理员登陆", "提示!");
}
else
{
MessageBox.Show( //如果是user登陆则提示普通用户登陆
"普通用户登陆", "提示!");
}
}
}
}
?
?????如果不希望用户更改ComboBox下拉列表中选中的内容,可以设置DropDownStyle属性为DropDownList,这样登录选项就变成了只读。