圖示
實現過程
1.設計界面
2.設計控件及其屬性
3.實現點擊事件、顯示事件以及運算
4實現功能
代碼如下
private void Form1_Load(object sender, EventArgs e)
{
// 給FlowLayoutPanel控件添加tag屬性,編號爲index, 菜名爲name,價格爲money
//根據菜品的數量 添加對應的序號按鈕
foreach (Control item in flowLayoutPanel1.Controls)//找到菜單中所有的panel控件
{ //就是創建Button對象 使用關鍵new創建對象
Button btn = new Button(); // 實例化button對象
// 將每一個子控件賦值給對應按鈕的Tag屬性
btn.Tag = item;
btn.Size = new Size(50, 25);//設置點擊按鈕的大小
btn.Font = new Font("宋體", 18F);//設置按鈕顯示字體及其字體大小
foreach (Control control in item.Controls)
{
//根據控件的Tag屬性值來判斷以及獲取對應控件中的文本從而設置給btn.Text
// 如果Tag爲index 那就是編號
if (control.Tag.ToString() == "index")
{
btn.Text = control.Text;
}
}
flowLayoutPanel2.Controls.Add(btn);
//加載時顯示按鈕
btn.Click += Btn_Click; // 添加點擊事件+=
}
}
int count = 0; // 價格金額
private void Btn_Click(object sender, EventArgs e)
{
Button clickBtn = (Button)sender;
Label lab = new Label();
//獲取菜單中每一個子控件中的菜名與價格
// 獲取到編號按鈕對應的菜單子控件
Control menu = (Control)clickBtn.Tag;
// 遍歷的是菜單中的子控件
foreach (Control item in menu.Controls)
{
if (item.Tag.ToString() == "name")
{
lab.Text = item.Text;
}
if (item.Tag.ToString() == "money")
{
//int.Parse(需要轉換的字符串)
//將字符串轉換爲數字的方法
count += int.Parse(item.Text);
}
}
flowLayoutPanel3.Controls.Add(lab);//(點擊事件)顯示點擊過的菜名
label18.Text = count + "元";//總共點過菜的金額總和
}