将列表添加到<string>数据网格视图行



我是使用 DataGridView 组件的新手,我以前使用过一次并设法完成了这个确切的任务,但我忘记了我是如何实现它的。

基本上,我想从格式如下的文本文件中读取值: line 1, line 2, line 3

这是我目前拥有的代码:

List<string> tokens = new List<string>();
private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
string[] lines = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach (var line in lines)
{
using (StreamReader sr = new StreamReader(Path.GetFullPath(line)))
{
var l = sr.ReadLine();
string[] data;
while (l != null)
{
data = l.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
l = sr.ReadLine();
tokens.Add(l);
}
}
}
for (int i = 0; i < tokens.Count - 1; i++)
{
dataGridView1.Rows[i].Cells[0].Selected = true;
dataGridView1.CurrentCell.Value = tokens[i];
}
}

当前代码导致line 2仅添加到 datagridview,而没有其他任何内容。 我想将每一行添加到每行的第一列中,具体取决于文本文件中的行数。

希望这是有道理的,非常感谢!

你可以试试这个:

private void dataGridView1_DragDrop(object sender, DragEventArgs e)
{
dataGridView1.Columns.Add("Value", "Value");
var files = (string[])e.Data.GetData(DataFormats.FileDrop, false);
foreach ( var file in files )
{
var lines = File.ReadAllLines(Path.GetFullPath(file));
foreach ( string line in lines )
dataGridView1.Rows.Add(line.TrimEnd(','));
}
}
private void dataGridView1_DragEnter(object sender, DragEventArgs e)
{
if ( e.Data.GetDataPresent(DataFormats.FileDrop) )
e.Effect = DragDropEffects.Move;
else
e.Effect = DragDropEffects.None;
}

最新更新