需要搜索整个数组,而不是一个
本文关键字:一个 搜索 数组 | 更新日期: 2023-09-27 17:51:09
抱歉我问了太多问题但我有一个问题当我比较数组中的字符串时它只会搜索数组的一个实例,例如程序允许你向数组中添加患者但当我使用比较字符串时它只会比较最后添加的患者,你能帮我吗?
这是我的程序:
public class Patient
{
public string patientidString;
public string firstNameString;
public string lastNameString;
public string dateString;
public Patient()
{
patientidString = "";
firstNameString = "";
lastNameString = "";
dateString = "";
}
public Patient(string idValue, string firstNameVal, string lastNameVal, string dateVal)
{
patientidString = idValue;
firstNameString = firstNameVal;
lastNameString = lastNameVal;
dateString = dateVal;
}
}
//Array
Patient[] patientInfo = new Patient[10];
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < patientInfo.Length; ++i)
patientInfo[i] = new Patient();
try
{
foreach (Patient patientinfoIndex in patientInfo)
patientInfo[itemCountInteger].patientidString = textBox1.Text;
patientInfo[itemCountInteger].firstNameString = textBox2.Text;
patientInfo[itemCountInteger].lastNameString = textBox3.Text;
patientInfo[itemCountInteger].dateString = dateTimePicker1.Text;
string names = patientInfo[itemCountInteger].patientidString + " " + patientInfo[itemCountInteger].firstNameString + " " + patientInfo[itemCountInteger].lastNameString;
listBox1.Items.Add(names);
itemCountInteger++;
listBox1.SelectedItem = names;
}
catch
{
MessageBox.Show("Contacts are limited to 20. Please delete some contacts prior to adding more.");
}
}
//Search Button search a patients id and display his surname in the label if patient is found display his surname and name
private void button2_Click(object sender, EventArgs e)
{
int intTest = 0;
for (int x = 0; x < patientInfo.Length; x++)
{
if (textBox4.Text == patientInfo[x].patientidString)
{
label6.Text = (patientInfo[x].firstNameString + " " + patientInfo[x].lastNameString);
PatientForm patientform = new PatientForm();
patientform.Show();
patientform.label6.Text = (patientInfo[x].patientidString);
patientform.label7.Text = (patientInfo[x].firstNameString);
patientform.label8.Text =(patientInfo[x].lastNameString);
patientform.dateTimePicker1.Text = (patientInfo[x].dateString);
intTest = 1;
}
}
if (intTest == 0)
{
label6.Text = ("not found");
}
}
如果您使用的是foreach
循环,则不需要使用索引器,
foreach (Patient patientinfoIndex in patientInfo)
{
patientinfoIndex.patientidString = textBox1.Text;
patientinfoIndex.firstNameString = textBox2.Text;
patientinfoIndex.lastNameString = textBox3.Text;
patientinfoIndex.dateString = dateTimePicker1.Text;
string names =
patientinfoIndex.patientidString + " " +
patientinfoIndex.firstNameString + " " +
patientinfoIndex.lastNameString;
listBox1.Items.Add(names);
listBox1.SelectedItem = names;
}
您还缺少大括号{
}
,这将导致循环只执行循环声明后的第一个语句,而不执行其余的。
我假设您的button1_Click
函数绑定到添加新患者按钮。
代码行数
for (int i = 0; i < patientInfo.Length; ++i)
patientInfo[i] = new Patient();
正在清除您以前每次添加新患者时输入的所有患者数据!这就是为什么你在搜索时只能找到你输入的最后一个病人。您需要将这些代码行移到其他地方,例如表单类的构造函数。
在intTest = 1;
之后需要打破for
循环。
intTest = 1;
break;