如何添加整数,即。用于显示目的的计数变量?
int counter = 0;
private void btnDisplay_Click(object sender, EventArgs e)
{
StreamReader myReader = new StreamReader("StudentRecords.txt");
while (myReader.EndOfStream == false)
{
string[] storageArray = myReader.ReadLine().Split('#');
if (storageArray[0] == "S")
{
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Student Name: " + storageArray[1]);
lstDisplay.Items.Add("Student Number: " +storageArray[2]);
lstDisplay.Items.Add("Attendance: " + storageArray[5]);
lstDisplay.Items.Add("Modules: ");
counter++;
}
else if (storageArray[0] == "M")
{
lstDisplay.Items.Add(storageArray[1]);
}
}
//label to be used to display the number of students
lblnoOfStudents. ??
myReader.Close();
}
答案 0 :(得分:0)
将邮件分配到标签的Text
属性:
lblnoOfStudents.Text = string.Format("Students: {0}", counter);
答案 1 :(得分:0)
lblnoOfStudents.Text = counter.ToString();
这会将标签上的文字更改为该号码。如果您想在现有文字的末尾添加+=
:
lblnoOfStudents.Text += counter.ToString();
答案 2 :(得分:0)
您可以使用Label
控件的.Text
属性。等;
获取或设置Label控件的文本内容。
lblnoOfStudents.Text = counter.ToString();
这会使用counter
变量的字符串表示更改标签文字。
答案 3 :(得分:0)
下面是代码的工作示例
//int counter = 0; may as well move inside as it looks to be localised
private void btnDisplay_Click(object sender, EventArgs e)
{
StreamReader myReader = new StreamReader("StudentRecords.txt");
int counter = 0;
while (myReader.EndOfStream == false)
{
string[] storageArray = myReader.ReadLine().Split('#');
if (storageArray[0] = "S")
{
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Student Name: " + storageArray[1]);
lstDisplay.Items.Add("Student Number: " +storageArray[2]);
lstDisplay.Items.Add("Attendance: " + storageArray[5]);
lstDisplay.Items.Add("Modules: ");
counter++;
}
else if (storageArray[0] == "M")
{
lstDisplay.Items.Add(storageArray[1]);
}
}
//label to be used to display the number of students
lblnoOfStudents.Text = counter.ToString();
myReader.Close();
}
编辑:我觉得我应该改进我的答案,所以我想我只是改进你的代码。
//int counter = 0; may as well move inside as it looks to be localised
private void btnDisplay_Click(object sender, EventArgs e)
{
using(StreamReader myReader = new StreamReader("StudentRecords.txt"))
{
int counter = 0;
while (!myReader.EndOfStream)
{
string[] storageArray = myReader.ReadLine().Split('#');
switch(storageArray[0])
{
case "S":
lstDisplay.Items.Add("");
lstDisplay.Items.Add("Student Name: " + storageArray[1]);
lstDisplay.Items.Add("Student Number: " +storageArray[2]);
lstDisplay.Items.Add("Attendance: " + storageArray[5]);
lstDisplay.Items.Add("Modules: ");
counter++;
break;
case "M":
lstDisplay.Items.Add(storageArray[1]);
break;
default:
break;
}
}
}
//label to be used to display the number of students
lblnoOfStudents.Text = counter.ToString();
}
}
==false
是
冗余,因为你已经可以从左侧获得一个布尔值
这个运营商。