所以我有这个列表视图,我可以通过打开文件对话框向其添加项目,然后我执行File.ReadLine并通读我刚刚选择的文本文件的所有行。
假设我选择了一个包含 3 行的文本文件。
鲍勃猫人
然后它的作用是将项目添加到列表视图中。
现在,对于它添加的每个项目,我想递增标签(从 0> 3 添加)。
private void btnAddItems_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Names|*.txt";
if(ofd.ShowDialog() == DialogResult.OK)
{
string[] recipients = File.ReadAllLines(ofd.FileName);
foreach(string name in recipients)
{
lvRecipient.Items.Add(name);
//increment the number of items in the list
foreach(int item in lvRecipient.Items)
{
int i = 0;
i++;
lbCount.Text = i.ToString();
}
}
}
我试过了,但一运行就出现了错误,我很确定它不起作用,因为它背后没有真正的位置,如何使我的标签从 0> 3 递增(或文本文件中有多少项)?
要解决您提出的问题,可以这样做:
private void btnAddItems_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Names|*.txt";
if(ofd.ShowDialog() == DialogResult.OK)
{
string[] recipients = File.ReadAllLines(ofd.FileName);
foreach(var name in recipients)
{
lvRecipient.Items.Add(name);
lbCount.Text = lvRecipient.Items.Count.ToString();
}
}
}
最好在添加所有项目后只设置计数标签,而不是在每次添加新项目时都设置它,因为添加操作应该非常快,使得人类甚至不太可能检测到不断变化的数字。这可以像这样完成:
private void btnAddItems_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Names|*.txt";
if(ofd.ShowDialog() == DialogResult.OK)
{
string[] recipients = File.ReadAllLines(ofd.FileName);
foreach(var name in recipients)
{
lvRecipient.Items.Add(name);
}
lbCount.Text = lvRecipient.Items.Count.ToString();
}
}
using System;
using System.IO;
using System.Windows.Forms;
namespace Jonny
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnAddItems_Click(object sender, EventArgs e)
{
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Names|*.txt";
if (ofd.ShowDialog() == DialogResult.OK)
{
string[] recipients = File.ReadAllLines(ofd.FileName);
foreach (string name in recipients)
{
lvRecipient.Items.Add(name);
//increment the number of items in the list
foreach (var item in lvRecipient.Items)
{
int i = 0;
i++;
lbCount.Text = i.ToString();
}
}
}
}
}
}
}
它确实有效 - 我试过了。如果你只是将"int"更改为"var" - 因为"lvRecipient.Items"无法在foreach循环中被视为整数。
您正在寻找的,也许有人会发现它很有用,我的函数正在异步运行,我不得不调用标签。
delegate void SetTextCallback1(string name);
private void SetTextLabel(string name)
{
if (this.label1.InvokeRequired)
{
SetTextCallback1 d = new SetTextCallback1(SetTextLabel);
this.Invoke(d, new object[] { name });
}
else
{
this.label1.Text = name;
}
}
然后我使用了task.run:
await Task.Run(() => SetTextLabel(name));
当然,Task.Run 行位于一个包裹在异步函数中的循环中。