菜单案例
需求:
(1)界面设计
(2)使用代码创建按钮(创建button对象)
(3)解决添加对应菜品按钮的问题
(3)控件与控件之间的关联
(4)使用按钮点餐
(5)计算最后金额
1.界面设计
使用FlowLayoutPanel与Label工具设计界面
重点:
(1)使用Margin控制控件之间的距离
(2)使用Font改变文字的大小,字体
(3)为了在其他控件中能够更好的获取到这个FlowLayoutPanel中控件对应的数据以及区分控件,则需要给FlowLayoutPanel中所有的控件添加Tag标签(编号为index,商品名字为name,金额为money)
2.使用foreach(循环遍历控件/对象)添加序号按钮
(1)使用 第一个foreach循环找到菜单中所有的控件FlowLayoutPanel,而找到的每一个FlowLayoutPanel控件中,还包含有label控件集合
foreach (Control item in flowLayoutPanel1.Controls)//循环遍历控件
{
Button ai = new Button();//创建对象(实例化)
ai.Size = new Size(100, 60);
ai.Font = new Font("微软雅黑",20F);
foreach (Control control in item.Controls)
{
if (control.Tag.ToString()=="index")
{
ai.Text = control.Text;
}
}
flowLayoutPanel7.Controls.Add(ai);
}
(2)使用嵌套在第一个foreach中的第二个foreach循环找到每一个FlowLayoutPanel控件中的所有控件(label),那么我们可以根据控件的Tag属性值来获取对应控件中的文本从而设置给ai.text
foreach (Control control in item.Controls)
{
if (control.Tag.ToString()=="index")
{
ai.Text = control.Text;
}
}
3.使用按钮进行点餐
(1)生成点击事件
ai.Click += Ai_Click;//添加点击事件
//ai.Click -= Ai_Click; 取消点击事件
重点:
添加的事件为公共事件,需要考虑的是点击哪个按钮
(2)使用sender参数(是哪个对象触发的事件,sender就是谁)
Button button =(Button)sender;
(3)获取菜单中的每一个子控件
Control control = (Control)button.Tag;//获取到编号按钮对应的菜单子控件
(4)使用foreach遍历菜单中的子控件
foreach (Control item in control.Controls)
{
if (item.Tag.ToString() == "name") ;
{
lab.Text = item.Text;
}
}
重点:
(1)将每一个子控件赋值给对应按钮的Tag属性
ai.Tag = item;
(2)创建label控件
Label lab = new Label();//创建label控件
4.计算金额
(1)设置一个记录总价格的变量
int count = 0;//记录总价格的变量
(2)使用if计算
if (item.Tag.ToString()=="money")
{
//int.Parse(需要转换的字符串):将字符串转换为数字
count += int.Parse(item.Text);
}
重点:
int.Parse(需要转换的字符串):将字符串转换为数字
的字符串):将字符串转换为数字
count += int.Parse(item.Text);
}
**重点**
int.Parse(需要转换的字符串):将字符串转换为数字