我在将文本文件中的 3 条记录加载到数据 GridView 时遇到问题。
private void button1_Click(object sender, EventArgs e)
{
using (OpenFileDialog ofd = new OpenFileDialog())
{
if (ofd.ShowDialog() == DialogResult.OK && radioButton1.Checked)
{
System.IO.StreamReader file = new System.IO.StreamReader(ofd.FileName);
string[] columnnames = file.ReadLine().Split('|');
List<string> list = new List<string>();
DataTable dt = new DataTable();
foreach (string c in columnnames)
{
dt.Columns.Add(c);
}
string newline;
while ((newline = file.ReadLine()) != null)
{
DataRow dr = dt.NewRow();
string[] values = newline.Split('|');
for (int i = 0; i < values.Length; i++)
{
dr[i] = values[i];
}
dt.Rows.Add(dr);
}
file.Close();
dataGridView1.DataSource = dt;
}
}
我试图让某人选择一个单选按钮(例如“显示 3 条记录”)并打开一个文本文件。然后它将仅在 datagridview 中列出 3 条记录。我可以获取文件来加载文件,但无法弄清楚如何让它只显示文本文件中的 3 条记录。有人可以帮帮我吗?
最佳答案
var records = File.ReadLines(ofd.FileName).Take(3);
foreach(var record in records)
{
// do stuff
}
这种方法的优点在于,ReadLines
创建一个迭代器并调用 StreamReader
的管道并单独读取每一行。当与 Take
结合时,它只读取和加载迭代的内容(在本例中为前 3 行)。
您可以在此处找到(并遵循)源代码
https://referencesource.microsoft.com/mscorlib/R/d989485a49fbbfd2.html
其他资源
Reads the lines of a file.
Enumerable.Take(IEnumerable, Int32) Method
Returns a specified number of contiguous elements from the start of a sequence.
关于c# - 显示文本文件中特定数量的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55506345/