using system; using system.collections.generic; using system.componentmodel; using system.data; using system.drawing; using system.linq; using system.text; using system.windows.forms;
namespaceaddprogram { publicpartialclassform1 : form { publicform1() { initializecomponent(); }
privatevoidbtnadd_click(object sender, eventargs e) { if (txttotal.text == "") { messagebox.show("请输入题目数!", "错误"); return; } //判断题目数是否未填 panelquestion.autoscroll = true; //为panel添加滚动条 panelquestion.controls.clear(); //清空已有题目 int total = int.parse(txttotal.text); //题目总数 textbox txtbox = new textbox(); label label = new label(); random rand = new random(); //随机数 for (int i = 0; i < total; i++) { for(int j = 0; j < 3; j++) { txtbox = new textbox(); txtbox.size = new size(50, 50); //textbox大小 txtbox.location = new point(10 + 70 * j, 30 * i); //textbox坐标 txtbox.name = "txt" + convert.tostring(i); //设定控件名称 if (j < 2) { txtbox.text = convert.tostring(rand.next(100)); txtbox.readonly = true; } //产生随机数,作为加数 panelquestion.controls.add(txtbox); //把控件加入到panel中 label = new label(); label.size = new size(12, 12); label.location = new point(64 + 70 * j, 30 * i); switch (j) { case0: label.text = "+"; break; case1: label.text = "="; break; case2: label.name = "labelresult" + convert.tostring(i); break; } panelquestion.controls.add(label); } } }
privatevoidbtnjudge_click(object sender, eventargs e) { if (txttotal.text == "") { messagebox.show("请输入题目数!", "错误"); return; } int total = convert.toint32(txttotal.text); for (int i = 0; i < total; i++) { textbox[] txtbox = new textbox[3]; //用控件数组来定义每一行的textbox,总共3个textbox for (int j = 0; j < 3; j++) //获取原来已经动态添加的textbox,这样才能访问 txtbox[j] = (textbox)panelquestion.controls.find("txt" + convert.tostring(i), true)[j]; label label = (label)panelquestion.controls.find("labelresult" + convert.tostring(i), true)[0]; if (txtbox[2].text == "") //如果未填答案,直接批改为错误 { label.text = "×"; continue; } intadd = convert.toint32(txtbox[0].text) + convert.toint32(txtbox[1].text); if (add == convert.toint32(txtbox[2].text)) label.text = "√"; else label.text = "×"; } }