菜单案例

菜单案例

需求:

(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(需要转换的字符串):将字符串转换为数字

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值