C#——Windows程序, 输入联系人姓名和电话号码并保存到结构体数组中,
C#——Windows程序,
输入联系人姓名和电话号码并保存到结构体数组中,
使用foreach语句迭代查询指定联系人的电话号码
设计以下界面
编写代码
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;
namespace aa
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Contacts[] con=new Contacts [100];
int i = 0;
private void button1_Click(object sender, EventArgs e)
{
string x = textBox1.Text;
string y = textBox2.Text;
con[i].name = x;
con[i].phone = y;
i++;
label3.Text = "成功添加"+i+"条记录";
textBox1.Text = "";
textBox2.Text = "";
}
/*第一种方法
private void button2_Click(object sender, EventArgs e)
{
label5.Text = "查无此人";
foreach (Contacts xx in con)
{
if(xx.name ==textBox3.Text )
{
label5.Text = "查找成功!此人的电话号码为:"+xx.phone;
}
}
}*/
//第二种方法
private void button2_Click(object sender, EventArgs e)
{
Boolean flag = false;
foreach (Contacts xx in con)
{
if (xx.name == textBox3.Text)
{
flag = true;
label5.Text = "查找成功!此人的电话号码为:" + xx.phone;
}
}
if(flag==false)
{
label5.Text = "查无此人?";
}
}
}
struct Contacts
{
public string name;
public string phone;
}
}
运行结果: